code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig UpperCAmelCase__ = logging.get_logger(__name__) # General docstring UpperCAmelCase__ = "PoolFormerConfig" # Base docstring UpperCAmelCase__ = "sail/poolformer_s12" UpperCAmelCase__ = [1, 512, 7, 7] # Image classification docstring UpperCAmelCase__ = "sail/poolformer_s12" UpperCAmelCase__ = "tabby, tabby cat" UpperCAmelCase__ = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def _a ( a :Dict , a :float = 0.0 , a :bool = False ) -> Optional[Any]: if drop_prob == 0.0 or not training: return input a = 1 - drop_prob a = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets a = keep_prob + torch.rand(a , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize a = input.div(a ) * random_tensor return output class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : int , __UpperCAmelCase : Optional[float] = None ) ->None: """simple docstring""" super().__init__() a = drop_prob def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : torch.Tensor ) ->torch.Tensor: """simple docstring""" return drop_path(__UpperCAmelCase , self.drop_prob , self.training ) def __lowerCAmelCase ( self : int ) ->str: """simple docstring""" return "p={}".format(self.drop_prob ) class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : Any=None ) ->int: """simple docstring""" super().__init__() a = patch_size if isinstance(__UpperCAmelCase , collections.abc.Iterable ) else (patch_size, patch_size) a = stride if isinstance(__UpperCAmelCase , collections.abc.Iterable ) else (stride, stride) a = padding if isinstance(__UpperCAmelCase , collections.abc.Iterable ) else (padding, padding) a = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , kernel_size=__UpperCAmelCase , stride=__UpperCAmelCase , padding=__UpperCAmelCase ) a = norm_layer(__UpperCAmelCase ) if norm_layer else nn.Identity() def __lowerCAmelCase ( self : int , __UpperCAmelCase : Optional[int] ) ->List[str]: """simple docstring""" a = self.projection(__UpperCAmelCase ) a = self.norm(__UpperCAmelCase ) return embeddings class lowercase_ ( nn.GroupNorm ): '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : Union[str, Any] ) ->Dict: """simple docstring""" super().__init__(1 , __UpperCAmelCase , **__UpperCAmelCase ) class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : int , __UpperCAmelCase : Optional[Any] ) ->List[Any]: """simple docstring""" super().__init__() a = nn.AvgPoolad(__UpperCAmelCase , stride=1 , padding=pool_size // 2 , count_include_pad=__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : List[str] ) ->Union[str, Any]: """simple docstring""" return self.pool(__UpperCAmelCase ) - hidden_states class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : Dict ) ->List[Any]: """simple docstring""" super().__init__() a = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , 1 ) a = nn.Convad(__UpperCAmelCase , __UpperCAmelCase , 1 ) a = PoolFormerDropPath(__UpperCAmelCase ) if isinstance(config.hidden_act , __UpperCAmelCase ): a = ACTaFN[config.hidden_act] else: a = config.hidden_act def __lowerCAmelCase ( self : int , __UpperCAmelCase : Optional[int] ) ->List[Any]: """simple docstring""" a = self.conva(__UpperCAmelCase ) a = self.act_fn(__UpperCAmelCase ) a = self.drop(__UpperCAmelCase ) a = self.conva(__UpperCAmelCase ) a = self.drop(__UpperCAmelCase ) return hidden_states class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : int , __UpperCAmelCase : str , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple ) ->int: """simple docstring""" super().__init__() a = PoolFormerPooling(__UpperCAmelCase ) a = PoolFormerOutput(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = PoolFormerGroupNorm(__UpperCAmelCase ) a = PoolFormerGroupNorm(__UpperCAmelCase ) # Useful for training neural nets a = PoolFormerDropPath(__UpperCAmelCase ) if drop_path > 0.0 else nn.Identity() a = config.use_layer_scale if config.use_layer_scale: a = nn.Parameter( config.layer_scale_init_value * torch.ones((__UpperCAmelCase) ) , requires_grad=__UpperCAmelCase ) a = nn.Parameter( config.layer_scale_init_value * torch.ones((__UpperCAmelCase) ) , requires_grad=__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Dict ) ->Any: """simple docstring""" if self.use_layer_scale: a = self.pooling(self.before_norm(__UpperCAmelCase ) ) a = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection a = hidden_states + self.drop_path(__UpperCAmelCase ) a = () a = self.output(self.after_norm(__UpperCAmelCase ) ) a = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection a = hidden_states + self.drop_path(__UpperCAmelCase ) a = (output,) + outputs return outputs else: a = self.drop_path(self.pooling(self.before_norm(__UpperCAmelCase ) ) ) # First residual connection a = pooling_output + hidden_states a = () # Second residual connection inside the PoolFormerOutput block a = self.drop_path(self.output(self.after_norm(__UpperCAmelCase ) ) ) a = hidden_states + layer_output a = (output,) + outputs return outputs class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" super().__init__() a = config # stochastic depth decay rule a = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings a = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) a = nn.ModuleList(__UpperCAmelCase ) # Transformer blocks a = [] a = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers a = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __UpperCAmelCase , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__UpperCAmelCase ) ) a = nn.ModuleList(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Tuple=True ) ->Union[str, Any]: """simple docstring""" a = () if output_hidden_states else None a = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): a , a = layers # Get patch embeddings from hidden_states a = embedding_layer(__UpperCAmelCase ) # Send the embeddings through the blocks for _, blk in enumerate(__UpperCAmelCase ): a = blk(__UpperCAmelCase ) a = layer_outputs[0] if output_hidden_states: a = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__UpperCAmelCase , hidden_states=__UpperCAmelCase ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = PoolFormerConfig __snake_case = '''poolformer''' __snake_case = '''pixel_values''' __snake_case = True def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : List[str] ) ->Optional[Any]: """simple docstring""" if isinstance(__UpperCAmelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__UpperCAmelCase , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Union[str, Any]=False ) ->int: """simple docstring""" if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = value UpperCAmelCase__ = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" UpperCAmelCase__ = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , lowercase , ) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : str , __UpperCAmelCase : int ) ->Optional[Any]: """simple docstring""" super().__init__(__UpperCAmelCase ) a = config a = PoolFormerEncoder(__UpperCAmelCase ) # Initialize weights and apply final processing self.post_init() def __lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__UpperCAmelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[bool] = None , ) ->Union[Tuple, BaseModelOutputWithNoAttention]: """simple docstring""" a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) a = self.encoder( __UpperCAmelCase , output_hidden_states=__UpperCAmelCase , return_dict=__UpperCAmelCase , ) a = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__UpperCAmelCase , hidden_states=encoder_outputs.hidden_states , ) class lowercase_ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : Dict ) ->List[str]: """simple docstring""" super().__init__() a = nn.Linear(config.hidden_size , config.hidden_size ) def __lowerCAmelCase ( self : int , __UpperCAmelCase : Optional[Any] ) ->Union[str, Any]: """simple docstring""" a = self.dense(__UpperCAmelCase ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , lowercase , ) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : List[str] ) ->Any: """simple docstring""" super().__init__(__UpperCAmelCase ) a = config.num_labels a = PoolFormerModel(__UpperCAmelCase ) # Final norm a = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head a = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__UpperCAmelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__UpperCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[torch.LongTensor] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[bool] = None , ) ->Union[Tuple, ImageClassifierOutputWithNoAttention]: """simple docstring""" a = return_dict if return_dict is not None else self.config.use_return_dict a = self.poolformer( __UpperCAmelCase , output_hidden_states=__UpperCAmelCase , return_dict=__UpperCAmelCase , ) a = outputs[0] a = self.classifier(self.norm(__UpperCAmelCase ).mean([-2, -1] ) ) a = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: a = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): a = '''single_label_classification''' else: a = '''multi_label_classification''' if self.config.problem_type == "regression": a = MSELoss() if self.num_labels == 1: a = loss_fct(logits.squeeze() , labels.squeeze() ) else: a = loss_fct(__UpperCAmelCase , __UpperCAmelCase ) elif self.config.problem_type == "single_label_classification": a = CrossEntropyLoss() a = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": a = BCEWithLogitsLoss() a = loss_fct(__UpperCAmelCase , __UpperCAmelCase ) if not return_dict: a = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__UpperCAmelCase , logits=__UpperCAmelCase , hidden_states=outputs.hidden_states )
0
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = False while is_sorted is False: # Until all the indices are traversed keep looping __lowerCAmelCase = True for i in range(0 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False for i in range(1 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False return input_list if __name__ == "__main__": print("Enter list to be sorted") A : Union[str, Any] = [int(x) for x in input().split()] # inputing elements of the list in one line A : str = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
57
0
'''simple docstring''' from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCAmelCase_ ( snake_case_ : bool = True , *snake_case_ : Union[str, Any] , **snake_case_ : int ) -> Tuple: '''simple docstring''' if not is_tqdm_available(): raise ImportError("Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`." ) UpperCAmelCase_ = False if main_process_only: UpperCAmelCase_ = PartialState().local_process_index == 0 return _tqdm(*snake_case_ , **snake_case_ , disable=snake_case_ )
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =["""image_processor""", """tokenizer"""] __UpperCAmelCase : Optional[Any] ="""CLIPImageProcessor""" __UpperCAmelCase : Union[str, Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): __lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) __lowerCAmelCase = kwargs.pop("feature_extractor" ) __lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self , __a=None , __a=None , __a=None , **__a ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __lowerCAmelCase = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: __lowerCAmelCase = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: __lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): __lowerCAmelCase = self.tokenizer.model_input_names __lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
57
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> Optional[int]: # noqa: E741 """simple docstring""" lowercase__ = len(A ) lowercase__ = 0 lowercase__ = [0] * n lowercase__ = [False] * n lowercase__ = [False] * n def dfs(A , A , A , A ): if parent == root: out_edge_count += 1 lowercase__ = True lowercase__ = at for to in l[at]: if to == parent: pass elif not visited[to]: lowercase__ = dfs(A , A , A , A ) lowercase__ = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: lowercase__ = True # AP found via cycle if at == low[to]: lowercase__ = True else: lowercase__ = min(low[at] , A ) return out_edge_count for i in range(A ): if not visited[i]: lowercase__ = 0 lowercase__ = dfs(A , A , -1 , A ) lowercase__ = out_edge_count > 1 for x in range(len(A ) ): if is_art[x] is True: print(A ) # Adjacency list of graph lowerCamelCase : int = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
2
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class _UpperCamelCase : '''simple docstring''' pass
57
0
'''simple docstring''' import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer A : Union[str, Any] = flax_key_tuple[:-1] + ('''weight''',) A : Tuple = torch.permute(snake_case__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(snake_case__ ): # linear layer A : Any = flax_key_tuple[:-1] + ('''weight''',) A : Union[str, Any] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: A : int = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' if "metadata" in layer: A : Union[str, Any] = layer.split('''metadata''' ) A : List[Any] = ''''''.join(split_layer[0] )[:-1] A : int = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: A : Any = layer.split('''kvstore''' ) A : List[Any] = ''''''.join(split_layer[0] )[:-1] A : Optional[Any] = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: A : Union[str, Any] = layer.split('''/''' ) A : Optional[int] = '''/'''.join(split_layer[:-1] ) A : Optional[Any] = (split_layer[-1],) if "kvstore/path" in layer: A : int = F'{switch_checkpoint_path}/{checkpoint_info[layer]}' elif "kvstore/driver" in layer: A : int = '''file''' else: A : Any = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Optional[int] = rename_keys(snake_case__ ) A : Tuple = {} for k, v in current_block.items(): A : Tuple = v A : List[str] = new_current_block torch.save(snake_case__ , snake_case__ ) def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = WEIGHTS_NAME ): '''simple docstring''' A : Dict = convert_file_size_to_int(snake_case__ ) A : str = [] A : str = {} A : Any = 0 A : List[str] = 0 os.makedirs(snake_case__ , exist_ok=snake_case__ ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: A : Tuple = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] A : List[Any] = flatten_dict(snake_case__ , sep='''/''' ) A : List[str] = {} for layer in checkpoint_info.keys(): A, A, A : Tuple = get_key_and_tensorstore_dict( snake_case__ , snake_case__ , snake_case__ ) if curr_real_layer_name in all_layers: A : List[str] = content else: A : Optional[Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file A : Any = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() A : List[Any] = torch.tensor(snake_case__ ) A : int = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts A, A : int = rename_base_flax_keys(tuple(key.split('''/''' ) ) , snake_case__ ) A : Union[str, Any] = '''/'''.join(snake_case__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: A : List[Any] = os.path.join( snake_case__ , weights_name.replace('''.bin''' , F'-{len(snake_case__ )+1:05d}-of-???.bin' ) ) rename_and_save_block(snake_case__ , snake_case__ ) sharded_state_dicts.append(current_block.keys() ) del current_block A : Dict = {} A : List[Any] = 0 A : List[Any] = raw_weights.to(getattr(snake_case__ , snake_case__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block A : Optional[int] = os.path.join(snake_case__ , weights_name.replace('''.bin''' , F'-{len(snake_case__ )+1:05d}-of-???.bin' ) ) rename_and_save_block(snake_case__ , snake_case__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(snake_case__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index A : Union[str, Any] = {} A : List[str] = {} for idx, shard in enumerate(snake_case__ ): A : int = weights_name.replace( '''.bin''' , F'-{idx+1:05d}-of-{len(snake_case__ ):05d}.bin' ) # len(sharded_state_dicts):05d} A : Union[str, Any] = os.path.join(snake_case__ , weights_name.replace('''.bin''' , F'-{idx+1:05d}-of-???.bin' ) ) os.rename(snake_case__ , os.path.join(snake_case__ , snake_case__ ) ) A : str = shard for key in shard: A : Tuple = shard_file # Add the metadata A : Tuple = {'''total_size''': total_size} A : Optional[int] = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' ) as f: A : Union[str, Any] = json.dumps(snake_case__ , indent=2 , sort_keys=snake_case__ ) + '''\n''' f.write(snake_case__ ) return metadata, index if __name__ == "__main__": lowercase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) lowercase : List[str] = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def lowerCAmelCase_ ( ): '''simple docstring''' from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer A : Optional[Any] = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) A : Any = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) A : Any = TaTokenizer.from_pretrained('''t5-small''' ) A : Union[str, Any] = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' A : List[Any] = tokenizer(snake_case__ , return_tensors='''pt''' ).input_ids A : Optional[Any] = model.generate(snake_case__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
3
"""simple docstring""" import sys from collections import defaultdict class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): return self.node_position[vertex] def snake_case ( self , __a , __a ): __lowerCAmelCase = pos def snake_case ( self , __a , __a , __a , __a ): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCAmelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCAmelCase = 2 * start + 1 else: __lowerCAmelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCAmelCase , __lowerCAmelCase = heap[smallest_child], positions[smallest_child] __lowerCAmelCase , __lowerCAmelCase = ( heap[start], positions[start], ) __lowerCAmelCase , __lowerCAmelCase = temp, tempa __lowerCAmelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __a ) self.top_to_bottom(__a , __a , __a , __a ) def snake_case ( self , __a , __a , __a , __a ): __lowerCAmelCase = position[index] while index != 0: __lowerCAmelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCAmelCase = heap[parent] __lowerCAmelCase = position[parent] self.set_position(position[parent] , __a ) else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , __a ) break __lowerCAmelCase = parent else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , 0 ) def snake_case ( self , __a , __a ): __lowerCAmelCase = len(__a ) // 2 - 1 for i in range(__a , -1 , -1 ): self.top_to_bottom(__a , __a , len(__a ) , __a ) def snake_case ( self , __a , __a ): __lowerCAmelCase = positions[0] __lowerCAmelCase = sys.maxsize self.top_to_bottom(__a , 0 , len(__a ) , __a ) return temp def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = Heap() __lowerCAmelCase = [0] * len(_UpperCamelCase ) __lowerCAmelCase = [-1] * len(_UpperCamelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCAmelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCAmelCase = [] for vertex in range(len(_UpperCamelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_UpperCamelCase ) heap.node_position.append(_UpperCamelCase ) __lowerCAmelCase = [] __lowerCAmelCase = 1 __lowerCAmelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCAmelCase = 0 __lowerCAmelCase = distance heap.heapify(_UpperCamelCase , _UpperCamelCase ) for _ in range(1 , len(_UpperCamelCase ) ): __lowerCAmelCase = heap.delete_minimum(_UpperCamelCase , _UpperCamelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCAmelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_UpperCamelCase )] ): __lowerCAmelCase = distance heap.bottom_to_top( _UpperCamelCase , heap.get_position(_UpperCamelCase ) , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A : Optional[Any] = int(input("Enter number of edges: ").strip()) A : Dict = defaultdict(list) for _ in range(edges_number): A : str = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
57
0
'''simple docstring''' from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def a_ ( lowerCamelCase : Namespace ): return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) __snake_case =""" transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. """ class UpperCAmelCase_ ( __lowercase ): @staticmethod def __UpperCAmelCase ( UpperCAmelCase__ : ArgumentParser ) -> Optional[int]: lowerCAmelCase = parser.add_parser( 'convert' , help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' , ) train_parser.add_argument('--model_type' , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='Model\'s type.' ) train_parser.add_argument( '--tf_checkpoint' , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='TensorFlow checkpoint path or folder.' ) train_parser.add_argument( '--pytorch_dump_output' , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='Path to the PyTorch saved model output.' ) train_parser.add_argument('--config' , type=UpperCAmelCase__ , default='' , help='Configuration file path or folder.' ) train_parser.add_argument( '--finetuning_task_name' , type=UpperCAmelCase__ , default=UpperCAmelCase__ , help='Optional fine-tuning task name if the TF model was a finetuned model.' , ) train_parser.set_defaults(func=UpperCAmelCase__ ) def __init__( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : str , *UpperCAmelCase__ : List[str] , ) -> Optional[Any]: lowerCAmelCase = logging.get_logger('transformers-cli/converting' ) self._logger.info(F'''Loading model {model_type}''' ) lowerCAmelCase = model_type lowerCAmelCase = tf_checkpoint lowerCAmelCase = pytorch_dump_output lowerCAmelCase = config lowerCAmelCase = finetuning_task_name def __UpperCAmelCase ( self : List[str] ) -> Dict: if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(UpperCAmelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) if "ckpt" in self._tf_checkpoint.lower(): lowerCAmelCase = self._tf_checkpoint lowerCAmelCase = '' else: lowerCAmelCase = self._tf_checkpoint lowerCAmelCase = '' convert_transfo_xl_checkpoint_to_pytorch( UpperCAmelCase__ , self._config , self._pytorch_dump_output , UpperCAmelCase__ ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(UpperCAmelCase__ ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]' )
4
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() A : Tuple = logging.get_logger(__name__) A : Tuple = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] A : Optional[Any] = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = torch.load(_UpperCamelCase , map_location="cpu" ) return sd def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=rename_keys_prefix ): '''simple docstring''' __lowerCAmelCase = OrderedDict() __lowerCAmelCase = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __lowerCAmelCase = key for name_pair in rename_keys_prefix: __lowerCAmelCase = new_key.replace(name_pair[0] , name_pair[1] ) __lowerCAmelCase = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __lowerCAmelCase = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}." # Get Config if "pre" in checkpoint_path: __lowerCAmelCase = "pretraining" if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 1024} else: raise NotImplementedError(f"No implementation found for `{checkpoint_path}`." ) else: if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} __lowerCAmelCase = "multichoice" elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} __lowerCAmelCase = "vqa_advanced" elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048, "num_labels": 3129} __lowerCAmelCase = "vqa" elif "nlvr" in checkpoint_path: __lowerCAmelCase = { "visual_embedding_dim": 1024, "num_labels": 2, } __lowerCAmelCase = "nlvr" __lowerCAmelCase = VisualBertConfig(**_UpperCamelCase ) # Load State Dict __lowerCAmelCase = load_state_dict(_UpperCamelCase ) __lowerCAmelCase = get_new_dict(_UpperCamelCase , _UpperCamelCase ) if model_type == "pretraining": __lowerCAmelCase = VisualBertForPreTraining(_UpperCamelCase ) elif model_type == "vqa": __lowerCAmelCase = VisualBertForQuestionAnswering(_UpperCamelCase ) elif model_type == "nlvr": __lowerCAmelCase = VisualBertForVisualReasoning(_UpperCamelCase ) elif model_type == "multichoice": __lowerCAmelCase = VisualBertForMultipleChoice(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Save Checkpoints Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") A : Optional[int] = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
57
0
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase__ ( lowerCAmelCase): def __init__(self , UpperCAmelCase , UpperCAmelCase=1_3 , UpperCAmelCase=7 , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=9_9 , UpperCAmelCase=3_2 , UpperCAmelCase=5 , UpperCAmelCase=4 , UpperCAmelCase=3_7 , UpperCAmelCase="gelu" , UpperCAmelCase=0.1 , UpperCAmelCase=0.1 , UpperCAmelCase=5_1_2 , UpperCAmelCase=1_6 , UpperCAmelCase=2 , UpperCAmelCase=0.02 , UpperCAmelCase=False , UpperCAmelCase=True , UpperCAmelCase="None" , UpperCAmelCase=3 , UpperCAmelCase=4 , UpperCAmelCase=None , ) -> Any: _lowercase =parent _lowercase =batch_size _lowercase =seq_length _lowercase =is_training _lowercase =use_input_mask _lowercase =use_token_type_ids _lowercase =use_labels _lowercase =vocab_size _lowercase =hidden_size _lowercase =num_hidden_layers _lowercase =num_attention_heads _lowercase =intermediate_size _lowercase =hidden_act _lowercase =hidden_dropout_prob _lowercase =attention_probs_dropout_prob _lowercase =max_position_embeddings _lowercase =type_vocab_size _lowercase =type_sequence_label_size _lowercase =initializer_range _lowercase =num_labels _lowercase =num_choices _lowercase =relative_attention _lowercase =position_biased_input _lowercase =pos_att_type _lowercase =scope def __A (self ) -> Any: _lowercase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowercase =None if self.use_input_mask: _lowercase =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _lowercase =None if self.use_token_type_ids: _lowercase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowercase =None _lowercase =None _lowercase =None if self.use_labels: _lowercase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowercase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowercase =ids_tensor([self.batch_size] , self.num_choices ) _lowercase =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A (self ) -> Optional[int]: return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __A (self ) -> List[Any]: _lowercase =self.get_config() _lowercase =3_0_0 return config def __A (self , UpperCAmelCase ) -> Union[str, Any]: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[str]: _lowercase =DebertaModel(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _lowercase =model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase )[0] _lowercase =model(UpperCAmelCase , token_type_ids=UpperCAmelCase )[0] _lowercase =model(UpperCAmelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Dict: _lowercase =DebertaForMaskedLM(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _lowercase =model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[str]: _lowercase =self.num_labels _lowercase =DebertaForSequenceClassification(UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _lowercase =model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(UpperCAmelCase ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: _lowercase =self.num_labels _lowercase =DebertaForTokenClassification(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _lowercase =model(UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , labels=UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Any: _lowercase =DebertaForQuestionAnswering(config=UpperCAmelCase ) model.to(UpperCAmelCase ) model.eval() _lowercase =model( UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , start_positions=UpperCAmelCase , end_positions=UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A (self ) -> Any: _lowercase =self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ) =config_and_inputs _lowercase ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCamelCase__ ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase): SCREAMING_SNAKE_CASE__ = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = ( { '''feature-extraction''': DebertaModel, '''fill-mask''': DebertaForMaskedLM, '''question-answering''': DebertaForQuestionAnswering, '''text-classification''': DebertaForSequenceClassification, '''token-classification''': DebertaForTokenClassification, '''zero-shot''': DebertaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def __A (self ) -> List[str]: _lowercase =DebertaModelTester(self ) _lowercase =ConfigTester(self , config_class=UpperCAmelCase , hidden_size=3_7 ) def __A (self ) -> Dict: self.config_tester.run_common_tests() def __A (self ) -> Optional[int]: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*UpperCAmelCase ) def __A (self ) -> Tuple: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*UpperCAmelCase ) def __A (self ) -> List[str]: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*UpperCAmelCase ) def __A (self ) -> int: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*UpperCAmelCase ) def __A (self ) -> str: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*UpperCAmelCase ) @slow def __A (self ) -> Optional[int]: for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase =DebertaModel.from_pretrained(UpperCAmelCase ) self.assertIsNotNone(UpperCAmelCase ) @require_torch @require_sentencepiece @require_tokenizers class lowerCamelCase__ ( unittest.TestCase): @unittest.skip(reason='''Model not available yet''' ) def __A (self ) -> Optional[Any]: pass @slow def __A (self ) -> Any: _lowercase =DebertaModel.from_pretrained('''microsoft/deberta-base''' ) _lowercase =torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) _lowercase =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _lowercase =model(UpperCAmelCase , attention_mask=UpperCAmelCase )[0] # compare the actual values for a slice. _lowercase =torch.tensor( [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase , atol=1e-4 ) , f"{output[:, 1:4, 1:4]}" )
5
"""simple docstring""" class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [ [], [], [], ] def snake_case ( self , __a , __a ): try: if len(self.queues[priority] ) >= 1_00: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(__a ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def snake_case ( self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues ) ) class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): if len(self.queue ) == 1_00: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(__a ) def snake_case ( self ): if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(__a ) return data def __str__( self ): return str(self.queue ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
57
0
# This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def __lowerCAmelCase ( a__ , a__ , a__ , a__ ) -> str: __a = multiprocessing.Manager() __a = manager.list() __a = multiprocessing.Process(target=a__ , args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append('''timed out''' ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def __lowerCAmelCase ( a__ , a__ , a__ ) -> List[Any]: with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil __a = shutil.rmtree __a = os.rmdir __a = os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: __a = {} with swallow_io(): with time_limit(a__ ): exec(a__ , a__ ) result.append('''passed''' ) except TimeoutException: result.append('''timed out''' ) except BaseException as e: result.append(F"""failed: {e}""" ) # Needed for cleaning up. __a = rmtree __a = rmdir __a = chdir @contextlib.contextmanager def __lowerCAmelCase ( a__ ) -> str: def signal_handler(a__ , a__ ): raise TimeoutException('''Timed out!''' ) signal.setitimer(signal.ITIMER_REAL , a__ ) signal.signal(signal.SIGALRM , a__ ) try: yield finally: signal.setitimer(signal.ITIMER_REAL , 0 ) @contextlib.contextmanager def __lowerCAmelCase ( ) -> Tuple: __a = WriteOnlyStringIO() with contextlib.redirect_stdout(a__ ): with contextlib.redirect_stderr(a__ ): with redirect_stdin(a__ ): yield @contextlib.contextmanager def __lowerCAmelCase ( ) -> Tuple: with tempfile.TemporaryDirectory() as dirname: with chdir(a__ ): yield dirname class __A( a ): pass class __A( io.StringIO ): def SCREAMING_SNAKE_CASE_ ( self , *_snake_case , **_snake_case ) -> int: '''simple docstring''' raise OSError def SCREAMING_SNAKE_CASE_ ( self , *_snake_case , **_snake_case ) -> List[Any]: '''simple docstring''' raise OSError def SCREAMING_SNAKE_CASE_ ( self , *_snake_case , **_snake_case ) -> List[Any]: '''simple docstring''' raise OSError def SCREAMING_SNAKE_CASE_ ( self , *_snake_case , **_snake_case ) -> Optional[int]: '''simple docstring''' return False class __A( contextlib._RedirectStream ): # type: ignore snake_case_ = '''stdin''' @contextlib.contextmanager def __lowerCAmelCase ( a__ ) -> List[Any]: if root == ".": yield return __a = os.getcwd() os.chdir(a__ ) try: yield except BaseException as exc: raise exc finally: os.chdir(a__ ) def __lowerCAmelCase ( a__=None ) -> Union[str, Any]: if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS , (maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA , (maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK , (maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins __a = None __a = None import os __a = '''1''' __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None __a = None import shutil __a = None __a = None __a = None import subprocess __a = None # type: ignore __a = None import sys __a = None __a = None __a = None __a = None __a = None
6
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' 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\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) __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()
57
0
import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A : """simple docstring""" @staticmethod def snake_case__ ( *lowercase_ : Tuple,**lowercase_ : List[str] )-> Optional[Any]: '''simple docstring''' pass @is_pipeline_test @require_torch @require_vision class A ( unittest.TestCase ): """simple docstring""" lowerCamelCase = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def snake_case__ ( self : Dict,lowercase_ : Union[str, Any],lowercase_ : Optional[Any],lowercase_ : Tuple )-> int: '''simple docstring''' A__ = pipeline('visual-question-answering',model='hf-internal-testing/tiny-vilt-random-vqa' ) A__ = [ { 'image': Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'question': 'How many cats are there?', }, { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'question': 'How many cats are there?', }, ] return vqa_pipeline, examples def snake_case__ ( self : Optional[Any],lowercase_ : List[str],lowercase_ : Dict )-> Tuple: '''simple docstring''' A__ = vqa_pipeline(lowercase_,top_k=1 ) self.assertEqual( lowercase_,[ [{'score': ANY(lowercase_ ), 'answer': ANY(lowercase_ )}], [{'score': ANY(lowercase_ ), 'answer': ANY(lowercase_ )}], ],) @require_torch def snake_case__ ( self : List[str] )-> Optional[int]: '''simple docstring''' A__ = pipeline('visual-question-answering',model='hf-internal-testing/tiny-vilt-random-vqa' ) A__ = './tests/fixtures/tests_samples/COCO/000000039769.png' A__ = 'How many cats are there?' A__ = vqa_pipeline(image=lowercase_,question='How many cats are there?',top_k=2 ) self.assertEqual( lowercase_,[{'score': ANY(lowercase_ ), 'answer': ANY(lowercase_ )}, {'score': ANY(lowercase_ ), 'answer': ANY(lowercase_ )}] ) A__ = vqa_pipeline({'image': image, 'question': question},top_k=2 ) self.assertEqual( lowercase_,[{'score': ANY(lowercase_ ), 'answer': ANY(lowercase_ )}, {'score': ANY(lowercase_ ), 'answer': ANY(lowercase_ )}] ) @slow @require_torch def snake_case__ ( self : Dict )-> Optional[int]: '''simple docstring''' A__ = pipeline('visual-question-answering',model='dandelin/vilt-b32-finetuned-vqa' ) A__ = './tests/fixtures/tests_samples/COCO/000000039769.png' A__ = 'How many cats are there?' A__ = vqa_pipeline(image=lowercase_,question=lowercase_,top_k=2 ) self.assertEqual( nested_simplify(lowercase_,decimals=4 ),[{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) A__ = vqa_pipeline({'image': image, 'question': question},top_k=2 ) self.assertEqual( nested_simplify(lowercase_,decimals=4 ),[{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) A__ = vqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}],top_k=2 ) self.assertEqual( nested_simplify(lowercase_,decimals=4 ),[[{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]] * 2,) @require_tf @unittest.skip('Visual question answering not implemented in TF' ) def snake_case__ ( self : str )-> Optional[Any]: '''simple docstring''' pass
7
"""simple docstring""" def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = 1 while len(_UpperCamelCase ) < 1e6: constant.append(str(_UpperCamelCase ) ) i += 1 __lowerCAmelCase = "".join(_UpperCamelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
57
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint lowerCAmelCase_ = { '''169M''': 12, '''430M''': 24, '''1B5''': 24, '''3B''': 32, '''7B''': 32, '''14B''': 40, } lowerCAmelCase_ = { '''169M''': 7_68, '''430M''': 10_24, '''1B5''': 20_48, '''3B''': 25_60, '''7B''': 40_96, '''14B''': 51_20, } def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): snake_case_ = list(state_dict.keys() ) for name in state_dict_keys: snake_case_ = state_dict.pop(SCREAMING_SNAKE_CASE__ ) # emb -> embedding if name.startswith('''emb.''' ): snake_case_ = name.replace('''emb.''' , '''embeddings.''' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('''blocks.0.ln0''' ): snake_case_ = name.replace('''blocks.0.ln0''' , '''blocks.0.pre_ln''' ) # att -> attention snake_case_ = re.sub(R'''blocks\.(\d+)\.att''' , R'''blocks.\1.attention''' , SCREAMING_SNAKE_CASE__ ) # ffn -> feed_forward snake_case_ = re.sub(R'''blocks\.(\d+)\.ffn''' , R'''blocks.\1.feed_forward''' , SCREAMING_SNAKE_CASE__ ) # time_mix_k -> time_mix_key and reshape if name.endswith('''.time_mix_k''' ): snake_case_ = name.replace('''.time_mix_k''' , '''.time_mix_key''' ) # time_mix_v -> time_mix_value and reshape if name.endswith('''.time_mix_v''' ): snake_case_ = name.replace('''.time_mix_v''' , '''.time_mix_value''' ) # time_mix_r -> time_mix_key and reshape if name.endswith('''.time_mix_r''' ): snake_case_ = name.replace('''.time_mix_r''' , '''.time_mix_receptance''' ) if name != "head.weight": snake_case_ = '''rwkv.''' + name snake_case_ = weight return state_dict def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=None ): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('''No `--tokenizer_file` provided, we will use the default tokenizer.''' ) snake_case_ = 50277 snake_case_ = AutoTokenizer.from_pretrained('''EleutherAI/gpt-neox-20b''' ) else: snake_case_ = PreTrainedTokenizerFast(tokenizer_file=SCREAMING_SNAKE_CASE__ ) snake_case_ = len(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) # 2. Build the config snake_case_ = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: snake_case_ = candidate break if size is None: raise ValueError('''Could not infer the size, please provide it with the `--size` argument.''' ) if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''' ) snake_case_ = RwkvConfig( vocab_size=SCREAMING_SNAKE_CASE__ , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(SCREAMING_SNAKE_CASE__ ) # 3. Download model file then convert state_dict snake_case_ = hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case_ = torch.load(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) snake_case_ = convert_state_dict(SCREAMING_SNAKE_CASE__ ) # 4. Split in shards and save snake_case_, snake_case_ = shard_checkpoint(SCREAMING_SNAKE_CASE__ ) for shard_file, shard in shards.items(): torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if index is not None: snake_case_ = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save the index as well with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: snake_case_ = json.dumps(SCREAMING_SNAKE_CASE__ , indent=2 , sort_keys=SCREAMING_SNAKE_CASE__ ) + '''\n''' f.write(SCREAMING_SNAKE_CASE__ ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( '''Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.''' ) snake_case_ = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: snake_case_ = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('''Please provide a `model_name` to push the model to the Hub.''' ) snake_case_ = AutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ ) model.push_to_hub(SCREAMING_SNAKE_CASE__ , max_shard_size='''2GB''' ) tokenizer.push_to_hub(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--repo_id''', default=None, type=str, required=True, help='''Repo ID from which to pull the checkpoint.''' ) parser.add_argument( '''--checkpoint_file''', default=None, type=str, required=True, help='''Name of the checkpoint file in the repo.''' ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''Where to save the converted model.''' ) parser.add_argument( '''--tokenizer_file''', default=None, type=str, help='''Path to the tokenizer file to use (if not provided, only the model is converted).''', ) parser.add_argument( '''--size''', default=None, type=str, help='''Size of the model. Will be inferred from the `checkpoint_file` if not passed.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Push to the Hub the converted model.''', ) parser.add_argument( '''--model_name''', default=None, type=str, help='''Name of the pushed model on the Hub, including the username / organization.''', ) lowerCAmelCase_ = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
8
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs A : Union[str, Any] = imread(R"digital_image_processing/image_data/lena_small.jpg") A : Optional[Any] = cvtColor(img, COLOR_BGR2GRAY) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = cn.convert_to_negative(_UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def _lowerCamelCase ( ): '''simple docstring''' with Image.open("digital_image_processing/image_data/lena_small.jpg" ) as img: # Work around assertion for response assert str(cc.change_contrast(_UpperCamelCase , 110 ) ).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = imread("digital_image_processing/image_data/lena_small.jpg" , 0 ) # assert ambiguous array for all == True assert canny_img.all() __lowerCAmelCase = canny.canny(_UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def _lowerCamelCase ( ): '''simple docstring''' assert gg.gaussian_filter(_UpperCamelCase , 5 , sigma=0.9 ).all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __lowerCAmelCase = conv.img_convolve(_UpperCamelCase , _UpperCamelCase ).astype(_UpperCamelCase ) assert res.any() def _lowerCamelCase ( ): '''simple docstring''' assert med.median_filter(_UpperCamelCase , 3 ).any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase = sob.sobel_filter(_UpperCamelCase ) assert grad.any() and theta.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = sp.make_sepia(_UpperCamelCase , 20 ) assert sepia.all() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' __lowerCAmelCase = bs.Burkes(imread(_UpperCamelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' __lowerCAmelCase = rs.NearestNeighbour(imread(_UpperCamelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. __lowerCAmelCase = imread(_UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = image[x_coordinate][y_coordinate] __lowerCAmelCase = lbp.get_neighbors_pixel( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __lowerCAmelCase = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __lowerCAmelCase = lbp.local_binary_value(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert lbp_image.any()
57
0
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin __lowerCAmelCase : List[str] =get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right __lowerCAmelCase : str =2_5_0_0_0_4 __lowerCAmelCase : Any =2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class _lowercase ( A__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = MBartTokenizer SCREAMING_SNAKE_CASE__ : str = MBartTokenizerFast SCREAMING_SNAKE_CASE__ : List[Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = True def __magic_name__( self :List[str] ) -> str: super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE : Any = MBartTokenizer(lowerCAmelCase__ , keep_accents=lowerCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def __magic_name__( self :Any ) -> Tuple: __SCREAMING_SNAKE_CASE : Dict = MBartTokenizer(lowerCAmelCase__ , keep_accents=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __SCREAMING_SNAKE_CASE : Any = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase__ , [ 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''', '''é''', '''.''', ] , ) __SCREAMING_SNAKE_CASE : Any = tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) self.assertListEqual( lowerCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def __magic_name__( self :Dict ) -> Union[str, Any]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __SCREAMING_SNAKE_CASE : str = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-mbart''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __SCREAMING_SNAKE_CASE : Optional[int] = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_r.save_pretrained(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer_p.save_pretrained(lowerCAmelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) __SCREAMING_SNAKE_CASE : Dict = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(lowerCAmelCase__ , lowerCAmelCase__ ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE : str = tokenizer_r.from_pretrained(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.from_pretrained(lowerCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowerCAmelCase__ ) # Save tokenizer rust, legacy_format=True __SCREAMING_SNAKE_CASE : Optional[Any] = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : List[str] = tokenizer_r.save_pretrained(lowerCAmelCase__ , legacy_format=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer_p.save_pretrained(lowerCAmelCase__ ) # Checks it save with the same files self.assertSequenceEqual(lowerCAmelCase__ , lowerCAmelCase__ ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_r.from_pretrained(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer_p.from_pretrained(lowerCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) shutil.rmtree(lowerCAmelCase__ ) # Save tokenizer rust, legacy_format=False __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : Dict = tokenizer_r.save_pretrained(lowerCAmelCase__ , legacy_format=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = tokenizer_p.save_pretrained(lowerCAmelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __SCREAMING_SNAKE_CASE : Dict = tokenizer_r.from_pretrained(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer_p.from_pretrained(lowerCAmelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) shutil.rmtree(lowerCAmelCase__ ) @require_torch @require_sentencepiece @require_tokenizers class _lowercase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = '''facebook/mbart-large-en-ro''' SCREAMING_SNAKE_CASE__ : Optional[int] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] SCREAMING_SNAKE_CASE__ : Any = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] SCREAMING_SNAKE_CASE__ : Tuple = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def __magic_name__( cls :str ) -> int: __SCREAMING_SNAKE_CASE : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en_XX''' , tgt_lang='''ro_RO''' ) __SCREAMING_SNAKE_CASE : List[Any] = 1 return cls def __magic_name__( self :Optional[Any] ) -> Dict: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ar_AR'''] , 250_001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''en_EN'''] , 250_004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['''ro_RO'''] , 250_020 ) def __magic_name__( self :Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase__ ) def __magic_name__( self :List[Any] ) -> Tuple: self.assertIn(lowerCAmelCase__ , self.tokenizer.all_special_ids ) __SCREAMING_SNAKE_CASE : int = [RO_CODE, 884, 9_019, 96, 9, 916, 86_792, 36, 18_743, 15_596, 5, 2] __SCREAMING_SNAKE_CASE : str = self.tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCAmelCase__ ) self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token , lowerCAmelCase__ ) def __magic_name__( self :List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE : Optional[Any] = ['''this is gunna be a long sentence ''' * 20] assert isinstance(src_text[0] , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = 10 __SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer(lowerCAmelCase__ , max_length=lowerCAmelCase__ , truncation=lowerCAmelCase__ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , lowerCAmelCase__ ) self.assertEqual(len(lowerCAmelCase__ ) , lowerCAmelCase__ ) def __magic_name__( self :Any ) -> List[str]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR'''] ) , [250_026, 250_001] ) def __magic_name__( self :List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE : Any = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = MBartTokenizer.from_pretrained(lowerCAmelCase__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowerCAmelCase__ ) @require_torch def __magic_name__( self :Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase__ , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : List[Any] = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __magic_name__( self :Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE : int = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Optional[int] = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) __SCREAMING_SNAKE_CASE : str = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowerCAmelCase__ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __magic_name__( self :Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer(self.src_text , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=3 , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer( text_target=self.tgt_text , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=10 , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = targets['''input_ids'''] __SCREAMING_SNAKE_CASE : Any = shift_tokens_right(lowerCAmelCase__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def __magic_name__( self :Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE : Dict = self.tokenizer._build_translation_inputs( '''A test''' , return_tensors='''pt''' , src_lang='''en_XX''' , tgt_lang='''ar_AR''' ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { # A, test, EOS, en_XX '''input_ids''': [[62, 3_034, 2, 250_004]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 250_001, } , )
9
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : Optional[int] = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltCLIPTextConfig", "AltCLIPVisionConfig", ], "processing_altclip": ["AltCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = [ "ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "AltCLIPPreTrainedModel", "AltCLIPModel", "AltCLIPTextModel", "AltCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys A : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants __A = Mapping[str, np.ndarray] __A = Mapping[str, Any] # Is a nested dict. __A = 0.0_1 @dataclasses.dataclass(frozen=__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowercase_ = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowercase_ = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowercase_ = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowercase_ = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowercase_ = None # Optional remark about the protein. Included as a comment in output PDB # files lowercase_ = None # Templates used to generate this protein (prediction-only) lowercase_ = None # Chain corresponding to each parent lowercase_ = None def lowerCAmelCase_ ( __a ) -> Protein: """simple docstring""" lowerCamelCase__: Union[str, Any] =R"(\[[A-Z]+\]\n)" lowerCamelCase__: List[str] =[tag.strip() for tag in re.split(__a , __a ) if len(__a ) > 0] lowerCamelCase__: Iterator[Tuple[str, List[str]]] =zip(tags[0::2] , [l.split("\n" ) for l in tags[1::2]] ) lowerCamelCase__: List[str] =["N", "CA", "C"] lowerCamelCase__: int =None lowerCamelCase__: str =None lowerCamelCase__: Dict =None for g in groups: if "[PRIMARY]" == g[0]: lowerCamelCase__: Optional[Any] =g[1][0].strip() for i in range(len(__a ) ): if seq[i] not in residue_constants.restypes: lowerCamelCase__: Optional[int] ="X" # FIXME: strings are immutable lowerCamelCase__: Optional[int] =np.array( [residue_constants.restype_order.get(__a , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: lowerCamelCase__: List[List[float]] =[] for axis in range(3 ): tertiary.append(list(map(__a , g[1][axis].split() ) ) ) lowerCamelCase__: List[str] =np.array(__a ) lowerCamelCase__: List[str] =np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(__a ): lowerCamelCase__: str =np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: lowerCamelCase__: int =np.array(list(map({"-": 0, "+": 1}.get , g[1][0].strip() ) ) ) lowerCamelCase__: Dict =np.zeros( ( len(__a ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(__a ): lowerCamelCase__: int =1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=__a , atom_mask=__a , aatype=__a , residue_index=np.arange(len(__a ) ) , b_factors=__a , ) def lowerCAmelCase_ ( __a , __a = 0 ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =[] lowerCamelCase__: Optional[Any] =prot.remark if remark is not None: pdb_headers.append(F"""REMARK {remark}""" ) lowerCamelCase__: List[str] =prot.parents lowerCamelCase__: Optional[int] =prot.parents_chain_index if parents is not None and parents_chain_index is not None: lowerCamelCase__: int =[p for i, p in zip(__a , __a ) if i == chain_id] if parents is None or len(__a ) == 0: lowerCamelCase__: Optional[int] =["N/A"] pdb_headers.append(F"""PARENT {" ".join(__a )}""" ) return pdb_headers def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" lowerCamelCase__: List[str] =[] lowerCamelCase__: Any =pdb_str.split("\n" ) lowerCamelCase__: Optional[Any] =prot.remark if remark is not None: out_pdb_lines.append(F"""REMARK {remark}""" ) lowerCamelCase__: List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: lowerCamelCase__: int =[] if prot.parents_chain_index is not None: lowerCamelCase__: Dict[str, List[str]] ={} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(__a ) , [] ) parent_dict[str(__a )].append(__a ) lowerCamelCase__: List[Any] =max([int(__a ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): lowerCamelCase__: Optional[Any] =parent_dict.get(str(__a ) , ["N/A"] ) parents_per_chain.append(__a ) else: parents_per_chain.append(list(prot.parents ) ) else: lowerCamelCase__: Optional[Any] =[["N/A"]] def make_parent_line(__a ) -> str: return F"""PARENT {" ".join(__a )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) lowerCamelCase__: Optional[int] =0 for i, l in enumerate(__a ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(__a ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(__a ): lowerCamelCase__: Union[str, Any] =parents_per_chain[chain_counter] else: lowerCamelCase__: int =["N/A"] out_pdb_lines.append(make_parent_line(__a ) ) return "\n".join(__a ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" lowerCamelCase__: str =residue_constants.restypes + ["X"] def res_atoa(__a ) -> str: return residue_constants.restype_atoa.get(restypes[r] , "UNK" ) lowerCamelCase__: List[str] =residue_constants.atom_types lowerCamelCase__: List[str] =[] lowerCamelCase__: Any =prot.atom_mask lowerCamelCase__: str =prot.aatype lowerCamelCase__: Optional[int] =prot.atom_positions lowerCamelCase__: List[str] =prot.residue_index.astype(np.intaa ) lowerCamelCase__: List[str] =prot.b_factors lowerCamelCase__: str =prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("Invalid aatypes." ) lowerCamelCase__: str =get_pdb_headers(__a ) if len(__a ) > 0: pdb_lines.extend(__a ) lowerCamelCase__: Dict =aatype.shape[0] lowerCamelCase__: Dict =1 lowerCamelCase__: List[Any] =0 lowerCamelCase__: Optional[Any] =string.ascii_uppercase lowerCamelCase__: List[str] =None # Add all atom sites. for i in range(__a ): lowerCamelCase__: Any =res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(__a , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue lowerCamelCase__: Union[str, Any] ="ATOM" lowerCamelCase__: Union[str, Any] =atom_name if len(__a ) == 4 else F""" {atom_name}""" lowerCamelCase__: int ="" lowerCamelCase__: List[str] ="" lowerCamelCase__: int =1.0_0 lowerCamelCase__: Optional[int] =atom_name[0] # Protein supports only C, N, O, S, this works. lowerCamelCase__: Dict ="" lowerCamelCase__: Union[str, Any] ="A" if chain_index is not None: lowerCamelCase__: Any =chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! lowerCamelCase__: str =( F"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" F"""{res_name_a:>3} {chain_tag:>1}""" F"""{residue_index[i]:>4}{insertion_code:>1} """ F"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" F"""{occupancy:>6.2f}{b_factor:>6.2f} """ F"""{element:>2}{charge:>2}""" ) pdb_lines.append(__a ) atom_index += 1 lowerCamelCase__: Optional[Any] =i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: lowerCamelCase__: List[str] =True lowerCamelCase__: Optional[int] =chain_index[i + 1] if should_terminate: # Close the chain. lowerCamelCase__: str ="TER" lowerCamelCase__: List[Any] =( F"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(__a ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(__a , __a ) ) pdb_lines.append("END" ) pdb_lines.append("" ) return "\n".join(__a ) def lowerCAmelCase_ ( __a ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , ) -> Protein: """simple docstring""" return Protein( aatype=features["aatype"] , atom_positions=result["final_atom_positions"] , atom_mask=result["final_atom_mask"] , residue_index=features["residue_index"] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result["final_atom_mask"] ) , chain_index=__a , remark=__a , parents=__a , parents_chain_index=__a , )
10
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A : Dict = logging.getLogger(__name__) @dataclass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[float] =field( default=0.0 ,metadata={"""help""": """The label smoothing epsilon to apply (if not zero)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """Whether to SortishSamler or not."""} ) __UpperCAmelCase : bool =field( default=lowerCAmelCase__ ,metadata={"""help""": """Whether to use generate to calculate generative metrics (ROUGE, BLEU)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """whether to use adafactor"""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Encoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Decoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field(default=lowerCAmelCase__ ,metadata={"""help""": """Dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Attention dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[str] =field( default="""linear""" ,metadata={"""help""": F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} ,)
57
0
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'vocab_file': 'vocab.json', 'tokenizer_config_file': 'tokenizer_config.json', 'merges_file': 'merges.txt', } lowerCAmelCase__ = { 'vocab_file': { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json' ), }, 'tokenizer_config_file': { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json' ), }, 'merges_file': { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt' ), }, } lowerCAmelCase__ = '</w>' lowerCAmelCase__ = '@@ ' def _UpperCAmelCase (UpperCamelCase__ : Optional[Any] ): _A : Optional[int] = set() _A : Optional[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _A : List[Any] = char return pairs # Speech2Text2 has no max input length lowerCAmelCase__ = {'facebook/s2t-wav2vec2-large-en-de': 10_24} class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask"] def __init__( self , __lowerCamelCase , __lowerCamelCase="<s>" , __lowerCamelCase="<pad>" , __lowerCamelCase="</s>" , __lowerCamelCase="<unk>" , __lowerCamelCase=False , __lowerCamelCase=None , **__lowerCamelCase , ) -> Optional[Any]: super().__init__( unk_token=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , pad_token=__lowerCamelCase , do_lower_case=__lowerCamelCase , **__lowerCamelCase , ) _A : Dict = do_lower_case with open(__lowerCamelCase , encoding="utf-8") as vocab_handle: _A : Optional[int] = json.load(__lowerCamelCase) _A : Optional[Any] = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F"No merges files provided. {self.__class__.__name__} can only be used for decoding.") _A : Optional[Any] = None _A : Tuple = None else: with open(__lowerCamelCase , encoding="utf-8") as merges_handle: _A : Optional[int] = merges_handle.read().split("\n")[:-1] _A : Union[str, Any] = [tuple(merge.split()[:2]) for merge in merges] _A : Optional[int] = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase)))) _A : List[Any] = {} @property def _lowerCamelCase ( self) -> int: return len(self.decoder) def _lowerCamelCase ( self) -> Dict: return dict(self.encoder , **self.added_tokens_encoder) def _lowerCamelCase ( self , __lowerCamelCase) -> Dict: _A : Tuple = tuple(token[:-1]) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] _A : int = get_pairs(__lowerCamelCase) if not pairs: return token while True: _A : Any = min(__lowerCamelCase , key=lambda __lowerCamelCase: self.bpe_ranks.get(__lowerCamelCase , float("inf"))) if bigram not in self.bpe_ranks: break _A , _A : Optional[int] = bigram _A : int = [] _A : str = 0 while i < len(__lowerCamelCase): try: _A : str = word.index(__lowerCamelCase , __lowerCamelCase) except ValueError: new_word.extend(word[i:]) break else: new_word.extend(word[i:j]) _A : str = j if word[i] == first and i < len(__lowerCamelCase) - 1 and word[i + 1] == second: new_word.append(first + second) i += 2 else: new_word.append(word[i]) i += 1 _A : List[str] = tuple(__lowerCamelCase) _A : List[str] = new_word if len(__lowerCamelCase) == 1: break else: _A : List[Any] = get_pairs(__lowerCamelCase) _A : Tuple = " ".join(__lowerCamelCase) if word == "\n " + BPE_TOKEN_MERGES: _A : List[str] = "\n" + BPE_TOKEN_MERGES if word.endswith(__lowerCamelCase): _A : int = word.replace(__lowerCamelCase , "") _A : int = word.replace(" " , __lowerCamelCase) _A : Union[str, Any] = word return word def _lowerCamelCase ( self , __lowerCamelCase) -> Optional[Any]: if self.bpe_ranks is None: raise ValueError( "This tokenizer was instantiated without a `merges.txt` file, so" " that it can only be used for decoding, not for encoding." "Make sure to provide `merges.txt` file at instantiation to enable " "encoding.") if self.do_lower_case: _A : List[Any] = text.lower() _A : Optional[int] = text.split() _A : List[str] = [] for token in text: if token: split_tokens.extend(list(self.bpe(__lowerCamelCase).split(" "))) return split_tokens def _lowerCamelCase ( self , __lowerCamelCase) -> int: return self.encoder.get(__lowerCamelCase , self.encoder.get(self.unk_token)) def _lowerCamelCase ( self , __lowerCamelCase) -> str: _A : List[str] = self.decoder.get(__lowerCamelCase , self.unk_token) return result def _lowerCamelCase ( self , __lowerCamelCase) -> str: _A : str = " ".join(__lowerCamelCase) # make sure @@ tokens are concatenated _A : int = "".join(string.split(__lowerCamelCase)) return string def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase = None) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return _A : Any = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]) _A : Any = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]) with open(__lowerCamelCase , "w" , encoding="utf-8") as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase) + "\n") _A : Union[str, Any] = 0 if self.bpe_ranks is None: return (vocab_file,) with open(__lowerCamelCase , "w" , encoding="utf-8") as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowerCamelCase: kv[1]): if index != token_index: logger.warning( F"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!") _A : Optional[int] = token_index writer.write(" ".join(__lowerCamelCase) + "\n") index += 1 return (vocab_file, merges_file)
11
"""simple docstring""" import argparse import os import re import packaging.version A : Any = "examples/" A : Optional[Any] = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } A : Optional[int] = { "init": "src/transformers/__init__.py", "setup": "setup.py", } A : List[Any] = "README.md" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , _UpperCamelCase ) __lowerCAmelCase = re_pattern.sub(_UpperCamelCase , _UpperCamelCase ) with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for folder, directories, fnames in os.walk(_UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase , pattern="examples" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if not patch: update_version_in_examples(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(_UpperCamelCase ).groups()[0] return packaging.version.parse(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase=False ): '''simple docstring''' __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __lowerCAmelCase = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(f"Which version are you releasing? [{default_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = default_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase , patch=_UpperCamelCase ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = get_version() __lowerCAmelCase = f"{current_version.major}.{current_version.minor + 1}.0.dev0" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(f"Which version are we developing now? [{dev_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = dev_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") A : Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
57
0
import math import os import sys def lowerCamelCase__ ( A__ : str ): '''simple docstring''' __lowerCamelCase = """""" try: with open(A__ , """rb""" ) as binary_file: __lowerCamelCase = binary_file.read() for dat in data: __lowerCamelCase = f'{dat:08b}' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def lowerCamelCase__ ( A__ : dict[str, str] , A__ : str , A__ : int , A__ : str ): '''simple docstring''' lexicon.pop(A__ ) __lowerCamelCase = last_match_id if math.loga(A__ ).is_integer(): for curr_key in lexicon: __lowerCamelCase = """0""" + lexicon[curr_key] __lowerCamelCase = bin(A__ )[2:] def lowerCamelCase__ ( A__ : str ): '''simple docstring''' __lowerCamelCase = {"""0""": """0""", """1""": """1"""} __lowerCamelCase, __lowerCamelCase = """""", """""" __lowerCamelCase = len(A__ ) for i in range(len(A__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __lowerCamelCase = lexicon[curr_string] result += last_match_id add_key_to_lexicon(A__ , A__ , A__ , A__ ) index += 1 __lowerCamelCase = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": __lowerCamelCase = lexicon[curr_string] result += last_match_id return result def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = os.path.getsize(A__ ) __lowerCamelCase = bin(A__ )[2:] __lowerCamelCase = len(A__ ) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = 8 try: with open(A__ , """wb""" ) as opened_file: __lowerCamelCase = [ to_write[i : i + byte_length] for i in range(0 , len(A__ ) , A__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(A__ , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def lowerCamelCase__ ( A__ : str , A__ : str ): '''simple docstring''' __lowerCamelCase = read_file_binary(A__ ) __lowerCamelCase = compress_data(A__ ) __lowerCamelCase = add_file_length(A__ , A__ ) write_file_binary(A__ , A__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
12
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A : Tuple = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Dict = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : str = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys A : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase : Union[str, Any] = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attention.self""", """self.proj""": """output.dense""", """attention.self_mask""": """attn_mask""", """mlp.fc1""": """intermediate.dense""", """mlp.fc2""": """output.dense""", """norm1""": """layernorm_before""", """norm2""": """layernorm_after""", """bn0""": """batch_norm""", } lowerCAmelCase : int = AutoFeatureExtractor.from_pretrained("""laion/clap-htsat-unfused""", truncation="""rand_trunc""") def A_ ( _UpperCAmelCase , _UpperCAmelCase=False ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = create_model( "HTSAT-tiny" , "roberta" , _UpperCAmelCase , precision="fp32" , device="cuda:0" if torch.cuda.is_available() else "cpu" , enable_fusion=_UpperCAmelCase , fusion_type="aff_2d" if enable_fusion else None , ) return model, model_cfg def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = {} SCREAMING_SNAKE_CASE_: Tuple = R".*sequential.(\d+).*" SCREAMING_SNAKE_CASE_: Dict = R".*_projection.(\d+).*" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: SCREAMING_SNAKE_CASE_: Any = key.replace(_UpperCAmelCase , _UpperCAmelCase ) if re.match(_UpperCAmelCase , _UpperCAmelCase ): # replace sequential layers with list SCREAMING_SNAKE_CASE_: Optional[int] = re.match(_UpperCAmelCase , _UpperCAmelCase ).group(1 ) SCREAMING_SNAKE_CASE_: Dict = key.replace(f"sequential.{sequential_layer}." , f"layers.{int(_UpperCAmelCase )//3}.linear." ) elif re.match(_UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = int(re.match(_UpperCAmelCase , _UpperCAmelCase ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... SCREAMING_SNAKE_CASE_: Optional[int] = 1 if projecton_layer == 0 else 2 SCREAMING_SNAKE_CASE_: Dict = key.replace(f"_projection.{projecton_layer}." , f"_projection.linear{transformers_projection_layer}." ) if "audio" and "qkv" in key: # split qkv into query key and value SCREAMING_SNAKE_CASE_: Tuple = value SCREAMING_SNAKE_CASE_: List[str] = mixed_qkv.size(0 ) // 3 SCREAMING_SNAKE_CASE_: Any = mixed_qkv[:qkv_dim] SCREAMING_SNAKE_CASE_: Optional[int] = mixed_qkv[qkv_dim : qkv_dim * 2] SCREAMING_SNAKE_CASE_: Optional[Any] = mixed_qkv[qkv_dim * 2 :] SCREAMING_SNAKE_CASE_: str = query_layer SCREAMING_SNAKE_CASE_: int = key_layer SCREAMING_SNAKE_CASE_: List[Any] = value_layer else: SCREAMING_SNAKE_CASE_: int = value return model_state_dict def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] = init_clap(_UpperCAmelCase , enable_fusion=_UpperCAmelCase ) clap_model.eval() SCREAMING_SNAKE_CASE_: Union[str, Any] = clap_model.state_dict() SCREAMING_SNAKE_CASE_: Optional[int] = rename_state_dict(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = ClapConfig() SCREAMING_SNAKE_CASE_: Tuple = enable_fusion SCREAMING_SNAKE_CASE_: Tuple = ClapModel(_UpperCAmelCase ) # ignore the spectrogram embedding layer model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) transformers_config.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument("""--enable_fusion""", action="""store_true""", help="""Whether to enable fusion or not""") lowerCAmelCase : int = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
13
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase = 6008_5147_5143 ): '''simple docstring''' try: __lowerCAmelCase = int(_UpperCamelCase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) __lowerCAmelCase = 2 __lowerCAmelCase = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 __lowerCAmelCase = i while n % i == 0: __lowerCAmelCase = n // i i += 1 return int(_UpperCamelCase ) if __name__ == "__main__": print(f'''{solution() = }''')
57
0
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : Dict = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ = SpeechTaTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = True def SCREAMING_SNAKE_CASE ( self : Any) ->Tuple: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = SpeechTaTokenizer(UpperCAmelCase__) A__ = AddedToken('''<mask>''' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__) A__ = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token}) tokenizer.add_tokens(['''<ctc_blank>''']) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : List[Any]) ->List[Any]: '''simple docstring''' A__ = '''this is a test''' A__ = '''this is a test''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : Any=20 , UpperCAmelCase__ : int=5) ->Any: '''simple docstring''' A__ , A__ = self.get_input_output_texts(UpperCAmelCase__) A__ = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__) A__ = tokenizer.decode(UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__) return text, ids def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->int: '''simple docstring''' A__ = '''<pad>''' A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__) , UpperCAmelCase__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__) , UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[str]: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<s>''') self.assertEqual(vocab_keys[1] , '''<pad>''') self.assertEqual(vocab_keys[-4] , '''œ''') self.assertEqual(vocab_keys[-2] , '''<mask>''') self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''') self.assertEqual(len(UpperCAmelCase__) , 81) def SCREAMING_SNAKE_CASE ( self : List[Any]) ->List[str]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79) def SCREAMING_SNAKE_CASE ( self : str) ->Union[str, Any]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=UpperCAmelCase__) for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}"""): A__ = tokenizer.vocab_size A__ = len(UpperCAmelCase__) self.assertNotEqual(UpperCAmelCase__ , 0) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A__ = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] A__ = tokenizer.add_tokens(UpperCAmelCase__) A__ = tokenizer.vocab_size A__ = len(UpperCAmelCase__) self.assertNotEqual(UpperCAmelCase__ , 0) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) self.assertEqual(UpperCAmelCase__ , len(UpperCAmelCase__)) self.assertEqual(UpperCAmelCase__ , all_size + len(UpperCAmelCase__)) A__ = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=UpperCAmelCase__) self.assertGreaterEqual(len(UpperCAmelCase__) , 4) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) A__ = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} A__ = tokenizer.add_special_tokens(UpperCAmelCase__) A__ = tokenizer.vocab_size A__ = len(UpperCAmelCase__) self.assertNotEqual(UpperCAmelCase__ , 0) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__) self.assertEqual(UpperCAmelCase__ , len(UpperCAmelCase__)) self.assertEqual(UpperCAmelCase__ , all_size_a + len(UpperCAmelCase__)) A__ = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=UpperCAmelCase__) self.assertGreaterEqual(len(UpperCAmelCase__) , 6) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[0] , tokens[1]) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokens[-4]) self.assertEqual(tokens[0] , tokenizer.eos_token_id) self.assertEqual(tokens[-3] , tokenizer.pad_token_id) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Tuple: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : List[str]) ->List[Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tokenizer.tokenize('''This is a test''') # fmt: off self.assertListEqual(UpperCAmelCase__ , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t''']) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) A__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( UpperCAmelCase__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.''']) A__ = tokenizer.convert_tokens_to_ids(UpperCAmelCase__) # fmt: off self.assertListEqual(UpperCAmelCase__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26]) # fmt: on A__ = tokenizer.convert_ids_to_tokens(UpperCAmelCase__) self.assertListEqual( UpperCAmelCase__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.''']) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[Any]: '''simple docstring''' A__ = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off A__ = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=UpperCAmelCase__ , )
14
"""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 _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__( self , __a , __a=None , __a=True , __a=None , **__a ): __lowerCAmelCase = parent __lowerCAmelCase = config_class __lowerCAmelCase = has_text_modality __lowerCAmelCase = kwargs __lowerCAmelCase = common_properties def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = ( ["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(__a , __a ) , msg=f"`{prop}` does not exist" ) # Test that config has the common properties as setter for idx, name in enumerate(__a ): try: setattr(__a , __a , __a ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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(__a ): try: __lowerCAmelCase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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 ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , __a ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , "config.json" ) config_first.to_json_file(__a ) __lowerCAmelCase = self.config_class.from_json_file(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = "test" with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , __a ) config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a , subfolder=__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) __lowerCAmelCase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def snake_case ( self ): if self.config_class.is_composition: return __lowerCAmelCase = self.config_class() self.parent.assertIsNotNone(__a ) def snake_case ( self ): __lowerCAmelCase = copy.deepcopy(__a ) __lowerCAmelCase = self.config_class(**__a ) __lowerCAmelCase = [] 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(__a , __a ) != value: wrong_values.append((key, getattr(__a , __a ), value) ) if len(__a ) > 0: __lowerCAmelCase = "\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 ): 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()
57
0
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean SCREAMING_SNAKE_CASE :Dict = 0 SCREAMING_SNAKE_CASE :Optional[int] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] SCREAMING_SNAKE_CASE :Union[str, Any] = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right SCREAMING_SNAKE_CASE :Optional[int] = tuple[int, int] class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[int] ,A : int ,A : int ,A : int ,A : int ,A : int ,A : Node | None ,): __A = pos_x __A = pos_y __A = (pos_y, pos_x) __A = goal_x __A = goal_y __A = g_cost __A = parent __A = self.calculate_heuristic() __A = self.g_cost + self.h_cost def UpperCamelCase_ ( self : Optional[int] ): __A = self.pos_x - self.goal_x __A = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A ) + abs(A ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : Union[str, Any] ,A : Node ): return self.f_cost < other.f_cost class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : TPosition ,A : TPosition ): __A = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,0 ,A ) __A = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,9_99_99 ,A ) __A = [self.start] __A = [] __A = False def UpperCamelCase_ ( self : Dict ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() __A = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A ) self.closed_nodes.append(A ) __A = self.get_successors(A ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A ) else: # retrieve the best current path __A = self.open_nodes.pop(self.open_nodes.index(A ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A ) else: self.open_nodes.append(A ) return [self.start.pos] def UpperCamelCase_ ( self : List[str] ,A : Node ): __A = [] for action in delta: __A = parent.pos_x + action[1] __A = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A ,A ,self.target.pos_y ,self.target.pos_x ,parent.g_cost + 1 ,A ,) ) return successors def UpperCamelCase_ ( self : int ,A : Node | None ): __A = node __A = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) __A = current_node.parent path.reverse() return path class UpperCAmelCase : '''simple docstring''' def __init__( self : List[str] ,A : TPosition ,A : TPosition ): __A = AStar(A ,A ) __A = AStar(A ,A ) __A = False def UpperCamelCase_ ( self : List[str] ): while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() __A = self.fwd_astar.open_nodes.pop(0 ) __A = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A ,A ) self.fwd_astar.closed_nodes.append(A ) self.bwd_astar.closed_nodes.append(A ) __A = current_bwd_node __A = current_fwd_node __A = { self.fwd_astar: self.fwd_astar.get_successors(A ), self.bwd_astar: self.bwd_astar.get_successors(A ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A ) else: # retrieve the best current path __A = astar.open_nodes.pop( astar.open_nodes.index(A ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A ) else: astar.open_nodes.append(A ) return [self.fwd_astar.start.pos] def UpperCamelCase_ ( self : Dict ,A : Node ,A : Node ): __A = self.fwd_astar.retrace_path(A ) __A = self.bwd_astar.retrace_path(A ) bwd_path.pop() bwd_path.reverse() __A = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] SCREAMING_SNAKE_CASE :List[Any] = (0, 0) SCREAMING_SNAKE_CASE :int = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) SCREAMING_SNAKE_CASE :Dict = time.time() SCREAMING_SNAKE_CASE :Union[str, Any] = AStar(init, goal) SCREAMING_SNAKE_CASE :Union[str, Any] = a_star.search() SCREAMING_SNAKE_CASE :Optional[int] = time.time() - start_time print(f'''AStar execution time = {end_time:f} seconds''') SCREAMING_SNAKE_CASE :Tuple = time.time() SCREAMING_SNAKE_CASE :List[Any] = BidirectionalAStar(init, goal) SCREAMING_SNAKE_CASE :str = time.time() - bd_start_time print(f'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')
15
"""simple docstring""" A : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
57
0
"""simple docstring""" def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> str: return "\n".join( f"""{number} * {i} = {number * i}""" for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
16
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : str = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : str =["""input_ids""", """attention_mask"""] def __init__( self , __a="</s>" , __a="<unk>" , __a="<pad>" , __a=1_25 , __a=None , **__a , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __lowerCAmelCase = [f"<extra_id_{i}>" for i in range(__a )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __lowerCAmelCase = len(set(filter(lambda __a : bool("extra_id" in str(__a ) ) , __a ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the" " extra_ids tokens" ) __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else pad_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else eos_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else unk_token super().__init__( eos_token=__a , unk_token=__a , pad_token=__a , extra_ids=__a , additional_special_tokens=__a , **__a , ) __lowerCAmelCase = extra_ids __lowerCAmelCase = 2**8 # utf is 8 bits # define special tokens dict __lowerCAmelCase = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __lowerCAmelCase = len(self.special_tokens_encoder ) __lowerCAmelCase = len(__a ) for i, token in enumerate(__a ): __lowerCAmelCase = self.vocab_size + i - n __lowerCAmelCase = {v: k for k, v in self.special_tokens_encoder.items()} @property def snake_case ( self ): return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def snake_case ( self , __a , __a = None , __a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__a )) + [1] return ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] def snake_case ( self , __a ): if len(__a ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated" " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = self._add_eos_if_not_present(__a ) if token_ids_a is None: return token_ids_a else: __lowerCAmelCase = self._add_eos_if_not_present(__a ) return token_ids_a + token_ids_a def snake_case ( self , __a ): __lowerCAmelCase = [chr(__a ) for i in text.encode("utf-8" )] return tokens def snake_case ( self , __a ): if token in self.special_tokens_encoder: __lowerCAmelCase = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __lowerCAmelCase = self.added_tokens_encoder[token] elif len(__a ) != 1: __lowerCAmelCase = self.unk_token_id else: __lowerCAmelCase = ord(__a ) + self._num_special_tokens return token_id def snake_case ( self , __a ): if index in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[index] else: __lowerCAmelCase = chr(index - self._num_special_tokens ) return token def snake_case ( self , __a ): __lowerCAmelCase = B"" for token in tokens: if token in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.added_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.special_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) elif token in self.added_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) else: __lowerCAmelCase = bytes([ord(__a )] ) bstring += tok_string __lowerCAmelCase = bstring.decode("utf-8" , errors="ignore" ) return string def snake_case ( self , __a , __a = None ): return ()
57
0
"""simple docstring""" def _A ( UpperCamelCase_ : list, UpperCamelCase_ : list) -> float: '''simple docstring''' _validate_point(UpperCamelCase_) _validate_point(UpperCamelCase_) if len(UpperCamelCase_) != len(UpperCamelCase_): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(UpperCamelCase_, UpperCamelCase_))) def _A ( UpperCamelCase_ : list[float]) -> None: '''simple docstring''' if point: if isinstance(UpperCamelCase_, UpperCamelCase_): for item in point: if not isinstance(UpperCamelCase_, (int, float)): __lowercase = ( "Expected a list of numbers as input, found " F"""{type(UpperCamelCase_).__name__}""" ) raise TypeError(UpperCamelCase_) else: __lowercase = F"""Expected a list of numbers as input, found {type(UpperCamelCase_).__name__}""" raise TypeError(UpperCamelCase_) else: raise ValueError("Missing an input") def _A ( UpperCamelCase_ : list, UpperCamelCase_ : list) -> float: '''simple docstring''' _validate_point(UpperCamelCase_) _validate_point(UpperCamelCase_) if len(UpperCamelCase_) != len(UpperCamelCase_): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(UpperCamelCase_, UpperCamelCase_))) if __name__ == "__main__": import doctest doctest.testmod()
17
"""simple docstring""" import numpy # List of input, output pairs A : Any = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) A : str = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) A : Union[str, Any] = [2, 4, 1, 5] A : int = len(train_data) A : Dict = 0.009 def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase="train" ): '''simple docstring''' return calculate_hypothesis_value(_UpperCamelCase , _UpperCamelCase ) - output( _UpperCamelCase , _UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(len(_UpperCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=m ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(_UpperCamelCase ): if index == -1: summation_value += _error(_UpperCamelCase ) else: summation_value += _error(_UpperCamelCase ) * train_data[i][0][index] return summation_value def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = summation_of_cost_derivative(_UpperCamelCase , _UpperCamelCase ) / m return cost_derivative_value def _lowerCamelCase ( ): '''simple docstring''' global parameter_vector # Tune these values to set a tolerance value for predicted output __lowerCAmelCase = 0.00_00_02 __lowerCAmelCase = 0 __lowerCAmelCase = 0 while True: j += 1 __lowerCAmelCase = [0, 0, 0, 0] for i in range(0 , len(_UpperCamelCase ) ): __lowerCAmelCase = get_cost_derivative(i - 1 ) __lowerCAmelCase = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( _UpperCamelCase , _UpperCamelCase , atol=_UpperCamelCase , rtol=_UpperCamelCase , ): break __lowerCAmelCase = temp_parameter_vector print(("Number of iterations:", j) ) def _lowerCamelCase ( ): '''simple docstring''' for i in range(len(_UpperCamelCase ) ): print(("Actual output value:", output(_UpperCamelCase , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(_UpperCamelCase , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
57
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml __lowerCamelCase : Any = logging.get_logger(__name__) def _snake_case ( lowerCAmelCase : bool , lowerCAmelCase : bool ): """simple docstring""" def run_func(lowerCAmelCase : int ): @wraps(lowerCAmelCase ) def run_in_eager_mode(*lowerCAmelCase : Tuple , **lowerCAmelCase : Any ): return func(*lowerCAmelCase , **lowerCAmelCase ) @wraps(lowerCAmelCase ) @tf.function(experimental_compile=lowerCAmelCase ) def run_in_graph_mode(*lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : List[str] ): return func(*lowerCAmelCase , **lowerCAmelCase ) if do_eager_mode is True: if use_xla is not False: raise ValueError( "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`." ) return run_in_eager_mode else: return run_in_graph_mode return run_func def _snake_case ( lowerCAmelCase : int , lowerCAmelCase : int , lowerCAmelCase : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = random.Random() SCREAMING_SNAKE_CASE_ : str = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(lowerCAmelCase , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class a__ ( A__ ): A = 42 A = 42 A = "TensorFlow" @property def __UpperCamelCase ( self : str ): """simple docstring""" return tf.__version__ def __UpperCamelCase ( self : int,_A : str,_A : int,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) SCREAMING_SNAKE_CASE_ : Any = self._prepare_inference_func(_A,_A,_A ) return self._measure_speed(_inference ) def __UpperCamelCase ( self : str,_A : str,_A : int,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) SCREAMING_SNAKE_CASE_ : List[Any] = self._prepare_train_func(_A,_A,_A ) return self._measure_speed(_train ) def __UpperCamelCase ( self : Dict,_A : str,_A : int,_A : int ): """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx],_A ) SCREAMING_SNAKE_CASE_ : Tuple = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) SCREAMING_SNAKE_CASE_ : str = self._prepare_inference_func(_A,_A,_A ) return self._measure_memory(_inference ) def __UpperCamelCase ( self : Optional[Any],_A : str,_A : int,_A : int ): """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx],_A ) SCREAMING_SNAKE_CASE_ : Any = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) SCREAMING_SNAKE_CASE_ : str = self._prepare_train_func(_A,_A,_A ) return self._measure_memory(_train ) def __UpperCamelCase ( self : int,_A : str,_A : int,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError("Mixed precision is currently not supported." ) SCREAMING_SNAKE_CASE_ : Dict = ( hasattr(_A,"architectures" ) and isinstance(config.architectures,_A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE_ : List[Any] = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE_ : List[Any] = __import__("transformers",fromlist=[model_class] ) SCREAMING_SNAKE_CASE_ : Tuple = getattr(_A,_A ) SCREAMING_SNAKE_CASE_ : List[str] = model_cls(_A ) except ImportError: raise ImportError( F'{model_class} does not exist. If you just want to test the pretrained model, you might want to' " set `--only_pretrain_model` or `args.only_pretrain_model=True`." ) else: SCREAMING_SNAKE_CASE_ : Optional[int] = TF_MODEL_MAPPING[config.__class__](_A ) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE_ : Tuple = config.vocab_size if hasattr(_A,"vocab_size" ) else config.encoder.vocab_size SCREAMING_SNAKE_CASE_ : str = random_input_ids(_A,_A,_A ) @run_with_tf_optimizations(self.args.eager_mode,self.args.use_xla ) def encoder_decoder_forward(): return model(_A,decoder_input_ids=_A,training=_A ) @run_with_tf_optimizations(self.args.eager_mode,self.args.use_xla ) def encoder_forward(): return model(_A,training=_A ) SCREAMING_SNAKE_CASE_ : Tuple = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def __UpperCamelCase ( self : Dict,_A : str,_A : int,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`." ) if self.args.fpaa: raise NotImplementedError("Mixed precision is currently not supported." ) SCREAMING_SNAKE_CASE_ : Dict = ( hasattr(_A,"architectures" ) and isinstance(config.architectures,_A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE_ : Dict = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE_ : Tuple = __import__("transformers",fromlist=[model_class] ) SCREAMING_SNAKE_CASE_ : Optional[int] = getattr(_A,_A ) SCREAMING_SNAKE_CASE_ : List[Any] = model_cls(_A ) except ImportError: raise ImportError( F'{model_class} does not exist. If you just want to test the pretrained model, you might want to' " set `--only_pretrain_model` or `args.only_pretrain_model=True`." ) else: SCREAMING_SNAKE_CASE_ : Any = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_A ) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE_ : Any = config.vocab_size if hasattr(_A,"vocab_size" ) else config.encoder.vocab_size SCREAMING_SNAKE_CASE_ : int = random_input_ids(_A,_A,_A ) @run_with_tf_optimizations(self.args.eager_mode,self.args.use_xla ) def encoder_decoder_train(): SCREAMING_SNAKE_CASE_ : Dict = model(_A,decoder_input_ids=_A,labels=_A,training=_A )[0] SCREAMING_SNAKE_CASE_ : Optional[Any] = tf.gradients(_A,model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode,self.args.use_xla ) def encoder_train(): SCREAMING_SNAKE_CASE_ : Tuple = model(_A,labels=_A,training=_A )[0] SCREAMING_SNAKE_CASE_ : Tuple = tf.gradients(_A,model.trainable_variables ) return gradients SCREAMING_SNAKE_CASE_ : List[Any] = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def __UpperCamelCase ( self : int,_A : Any ): """simple docstring""" with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info("Do inference on TPU. Running model 5 times to stabilize compilation" ) timeit.repeat(_A,repeat=1,number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average SCREAMING_SNAKE_CASE_ : Optional[int] = timeit.repeat( _A,repeat=self.args.repeat,number=10,) return min(_A ) / 10.0 except ResourceExhaustedError as e: self.print_fn(F'Doesn\'t fit on GPU. {e}' ) def __UpperCamelCase ( self : List[str],_A : Callable[[], None] ): """simple docstring""" logger.info( "Note that TensorFlow allocates more memory than " "it might need to speed up computation. " "The memory reported here corresponds to the memory " "reported by `nvidia-smi`, which can vary depending " "on total available memory on the GPU that is used." ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory" " consumption line by line." ) SCREAMING_SNAKE_CASE_ : List[str] = start_memory_tracing("transformers" ) if self.args.is_tpu: # tpu raise NotImplementedError( "Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking" " with `args.memory=False`" ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( "py3nvml not installed, we won't log GPU memory usage. " "Install py3nvml (pip install py3nvml) to log information about GPU." ) SCREAMING_SNAKE_CASE_ : Optional[int] = "N/A" else: logger.info( "Measuring total GPU usage on GPU device. Make sure to not have additional processes" " running on the same GPU." ) # init nvml nvml.nvmlInit() func() SCREAMING_SNAKE_CASE_ : str = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = nvml.nvmlDeviceGetMemoryInfo(_A ) SCREAMING_SNAKE_CASE_ : Any = meminfo.used SCREAMING_SNAKE_CASE_ : List[Any] = Memory(_A ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( "When enabling line by line tracing, the max peak memory for CPU is inaccurate in" " TensorFlow." ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None else: SCREAMING_SNAKE_CASE_ : Optional[Any] = measure_peak_memory_cpu(_A ) SCREAMING_SNAKE_CASE_ : str = Memory(_A ) if isinstance(_A,_A ) else memory_bytes if self.args.trace_memory_line_by_line: SCREAMING_SNAKE_CASE_ : Optional[int] = stop_memory_tracing(_A ) if memory is None: SCREAMING_SNAKE_CASE_ : Optional[Any] = summary.total else: SCREAMING_SNAKE_CASE_ : Optional[int] = None return memory, summary except ResourceExhaustedError as e: self.print_fn(F'Doesn\'t fit on GPU. {e}' ) return "N/A", None
18
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): __lowerCAmelCase = tempfile.mkdtemp() __lowerCAmelCase = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "的", "价", "格", "是", "15", "便", "alex", "##andra", ",", "。", "-", "t", "shirt", ] __lowerCAmelCase = 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] ) ) __lowerCAmelCase = { "do_resize": True, "size": {"height": 2_24, "width": 2_24}, "do_center_crop": True, "crop_size": {"height": 18, "width": 18}, "do_normalize": True, "image_mean": [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], "image_std": [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], "do_convert_rgb": True, } __lowerCAmelCase = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(__a , __a ) def snake_case ( self , **__a ): return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return BertTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self ): shutil.rmtree(self.tmpdirname ) def snake_case ( self ): __lowerCAmelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCAmelCase = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self ): __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__a ) __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __a ) self.assertIsInstance(processor_fast.tokenizer , __a ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __a ) self.assertIsInstance(processor_fast.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase = self.get_tokenizer(cls_token="(CLS)" , sep_token="(SEP)" ) __lowerCAmelCase = self.get_image_processor(do_normalize=__a ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="(CLS)" , sep_token="(SEP)" , do_normalize=__a ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = image_processor(__a , return_tensors="np" ) __lowerCAmelCase = processor(images=__a , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = processor(text=__a ) __lowerCAmelCase = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(__a ): processor() def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase = processor.batch_decode(__a ) __lowerCAmelCase = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
57
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer __A =logging.get_logger(__name__) __A ={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A ={ '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } __A ={ '''yjernite/retribert-base-uncased''': 5_1_2, } __A ={ '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class _SCREAMING_SNAKE_CASE ( snake_case_ ): lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase__ = RetriBertTokenizer lowerCAmelCase__ = ['input_ids', 'attention_mask'] def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> List[Any]: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowercase ) != do_lower_case or normalizer_state.get("strip_accents" , lowercase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowercase ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(lowercase , normalizer_state.pop("type" ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**lowercase ) lowerCamelCase_ = do_lower_case def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=None ) -> int: lowerCamelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = 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 ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = None ) -> Tuple[str]: lowerCamelCase_ = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
19
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( _UpperCamelCase = 4 ): '''simple docstring''' __lowerCAmelCase = abs(_UpperCamelCase ) or 4 return [[1 + x + y * row_size for x in range(_UpperCamelCase )] for y in range(_UpperCamelCase )] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(reverse_column(_UpperCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_column(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [list(_UpperCamelCase ) for x in zip(*_UpperCamelCase )] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = matrix[::-1] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [x[::-1] for x in matrix] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for i in matrix: print(*_UpperCamelCase ) if __name__ == "__main__": A : Dict = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_aa(matrix)) A : List[str] = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_aaa(matrix)) A : str = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_aaa(matrix))
57
0
import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __snake_case ( lowerCAmelCase , unittest.TestCase ): _a : str= None _a : int= BloomTokenizerFast _a : Optional[Any]= BloomTokenizerFast _a : Dict= True _a : str= False _a : Union[str, Any]= "tokenizer_file" _a : Union[str, Any]= {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"} def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' super().setUp() lowercase : Optional[int] = BloomTokenizerFast.from_pretrained("""bigscience/tokenizer""" ) tokenizer.save_pretrained(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self ,**snake_case ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = self.get_rust_tokenizer() lowercase : List[str] = ["""The quick brown fox</s>""", """jumps over the lazy dog</s>"""] lowercase : int = [[2175, 23714, 73173, 144252, 2], [77, 132619, 3478, 368, 109586, 35433, 2]] lowercase : int = tokenizer.batch_encode_plus(snake_case )["""input_ids"""] self.assertListEqual(snake_case ,snake_case ) lowercase : int = tokenizer.batch_decode(snake_case ) self.assertListEqual(snake_case ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case=6 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): lowercase : Optional[int] = self.rust_tokenizer_class.from_pretrained(snake_case ,**snake_case ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input lowercase : str = """This is a simple input""" lowercase : List[str] = ["""This is a simple input 1""", """This is a simple input 2"""] lowercase : Optional[int] = ("""This is a simple input""", """This is a pair""") lowercase : str = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests try: tokenizer_r.encode(snake_case ,max_length=snake_case ) tokenizer_r.encode_plus(snake_case ,max_length=snake_case ) tokenizer_r.batch_encode_plus(snake_case ,max_length=snake_case ) tokenizer_r.encode(snake_case ,max_length=snake_case ) tokenizer_r.batch_encode_plus(snake_case ,max_length=snake_case ) except ValueError: self.fail("""Bloom Tokenizer should be able to deal with padding""" ) lowercase : List[Any] = None # Hotfixing padding = None self.assertRaises(snake_case ,tokenizer_r.encode ,snake_case ,max_length=snake_case ,padding="""max_length""" ) # Simple input self.assertRaises(snake_case ,tokenizer_r.encode_plus ,snake_case ,max_length=snake_case ,padding="""max_length""" ) # Simple input self.assertRaises( snake_case ,tokenizer_r.batch_encode_plus ,snake_case ,max_length=snake_case ,padding="""max_length""" ,) # Pair input self.assertRaises(snake_case ,tokenizer_r.encode ,snake_case ,max_length=snake_case ,padding="""max_length""" ) # Pair input self.assertRaises(snake_case ,tokenizer_r.encode_plus ,snake_case ,max_length=snake_case ,padding="""max_length""" ) # Pair input self.assertRaises( snake_case ,tokenizer_r.batch_encode_plus ,snake_case ,max_length=snake_case ,padding="""max_length""" ,) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[Any] = self.get_rust_tokenizer() lowercase : Optional[Any] = load_dataset("""xnli""" ,"""all_languages""" ,split="""test""" ,streaming=snake_case ) lowercase : Tuple = next(iter(snake_case ) )["""premise"""] # pick up one data lowercase : Any = list(sample_data.values() ) lowercase : str = list(map(tokenizer.encode ,snake_case ) ) lowercase : Tuple = [tokenizer.decode(snake_case ,clean_up_tokenization_spaces=snake_case ) for x in output_tokens] self.assertListEqual(snake_case ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) ,1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) ,1 )
20
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCAmelCase : Union[str, Any] =TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = TextaTextGenerationPipeline(model=__a , tokenizer=__a ) return generator, ["Something to write", "Something else"] def snake_case ( self , __a , __a ): __lowerCAmelCase = generator("Something there" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["generated_text"].startswith("Something there" ) ) __lowerCAmelCase = generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) __lowerCAmelCase = generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) with self.assertRaises(__a ): generator(4 ) @require_torch def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="pt" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] ) __lowerCAmelCase = 3 __lowerCAmelCase = generator( "Something there" , num_return_sequences=__a , num_beams=__a , ) __lowerCAmelCase = [ {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": ""}, ] self.assertEqual(__a , __a ) __lowerCAmelCase = generator("This is a test" , do_sample=__a , num_return_sequences=2 , return_tensors=__a ) self.assertEqual( __a , [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ] , ) __lowerCAmelCase = generator.model.config.eos_token_id __lowerCAmelCase = "<pad>" __lowerCAmelCase = generator( ["This is a test", "This is a second test"] , do_sample=__a , num_return_sequences=2 , batch_size=2 , return_tensors=__a , ) self.assertEqual( __a , [ [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], ] , ) @require_tf def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="tf" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] )
57
0
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=99, lowerCamelCase=32, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=37, lowerCamelCase="gelu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=5_12, lowerCamelCase=16, lowerCamelCase=2, lowerCamelCase=0.0_2, lowerCamelCase=False, lowerCamelCase=True, lowerCamelCase="None", lowerCamelCase=3, lowerCamelCase=4, lowerCamelCase=None, ) -> str: """simple docstring""" _lowercase : Dict = parent _lowercase : Optional[int] = batch_size _lowercase : Tuple = seq_length _lowercase : Tuple = is_training _lowercase : Any = use_input_mask _lowercase : Optional[Any] = use_token_type_ids _lowercase : Tuple = use_labels _lowercase : Any = vocab_size _lowercase : int = hidden_size _lowercase : Optional[Any] = num_hidden_layers _lowercase : Optional[int] = num_attention_heads _lowercase : Union[str, Any] = intermediate_size _lowercase : str = hidden_act _lowercase : List[str] = hidden_dropout_prob _lowercase : Tuple = attention_probs_dropout_prob _lowercase : Tuple = max_position_embeddings _lowercase : int = type_vocab_size _lowercase : Tuple = type_sequence_label_size _lowercase : Any = initializer_range _lowercase : Optional[Any] = num_labels _lowercase : Tuple = num_choices _lowercase : Optional[int] = relative_attention _lowercase : Optional[int] = position_biased_input _lowercase : Tuple = pos_att_type _lowercase : Dict = scope def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : str = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) _lowercase : Any = None if self.use_input_mask: _lowercase : Optional[int] = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) _lowercase : Optional[int] = None if self.use_token_type_ids: _lowercase : List[Any] = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) _lowercase : List[str] = None _lowercase : Optional[int] = None _lowercase : List[Any] = None if self.use_labels: _lowercase : Union[str, Any] = ids_tensor([self.batch_size], self.type_sequence_label_size) _lowercase : Any = ids_tensor([self.batch_size, self.seq_length], self.num_labels) _lowercase : Optional[Any] = ids_tensor([self.batch_size], self.num_choices) _lowercase : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" return DebertaConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_range=self.initializer_range, relative_attention=self.relative_attention, position_biased_input=self.position_biased_input, pos_att_type=self.pos_att_type, ) def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : List[Any] = self.get_config() _lowercase : str = 3_00 return config def UpperCamelCase ( self, lowerCamelCase) -> Tuple: """simple docstring""" self.parent.assertListEqual(list(result.loss.size()), []) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> List[str]: """simple docstring""" _lowercase : Optional[int] = DebertaModel(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Optional[int] = model(lowerCamelCase, attention_mask=lowerCamelCase, token_type_ids=lowerCamelCase)[0] _lowercase : Union[str, Any] = model(lowerCamelCase, token_type_ids=lowerCamelCase)[0] _lowercase : Any = model(lowerCamelCase)[0] self.parent.assertListEqual(list(sequence_output.size()), [self.batch_size, self.seq_length, self.hidden_size]) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Optional[Any]: """simple docstring""" _lowercase : Dict = DebertaForMaskedLM(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : str = model(lowerCamelCase, attention_mask=lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Union[str, Any]: """simple docstring""" _lowercase : List[Any] = self.num_labels _lowercase : int = DebertaForSequenceClassification(lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Dict = model(lowerCamelCase, attention_mask=lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase) self.parent.assertListEqual(list(result.logits.size()), [self.batch_size, self.num_labels]) self.check_loss_output(lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Optional[int]: """simple docstring""" _lowercase : Union[str, Any] = self.num_labels _lowercase : Optional[int] = DebertaForTokenClassification(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : List[str] = model(lowerCamelCase, attention_mask=lowerCamelCase, token_type_ids=lowerCamelCase, labels=lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> int: """simple docstring""" _lowercase : Tuple = DebertaForQuestionAnswering(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Optional[Any] = model( lowerCamelCase, attention_mask=lowerCamelCase, token_type_ids=lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : List[Any] = self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ) : int = config_and_inputs _lowercase : Dict = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _lowerCamelCase( _a, _a, unittest.TestCase ): lowercase_ : Optional[int] = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ : Dict = ( { """feature-extraction""": DebertaModel, """fill-mask""": DebertaForMaskedLM, """question-answering""": DebertaForQuestionAnswering, """text-classification""": DebertaForSequenceClassification, """token-classification""": DebertaForTokenClassification, """zero-shot""": DebertaForSequenceClassification, } if is_torch_available() else {} ) lowercase_ : Union[str, Any] = True lowercase_ : Optional[int] = False lowercase_ : Union[str, Any] = False lowercase_ : Optional[int] = False lowercase_ : Dict = False def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : Any = DebertaModelTester(self) _lowercase : List[str] = ConfigTester(self, config_class=lowerCamelCase, hidden_size=37) def UpperCamelCase ( self) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCamelCase) def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*lowerCamelCase) def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*lowerCamelCase) @slow def UpperCamelCase ( self) -> Dict: """simple docstring""" for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : Optional[int] = DebertaModel.from_pretrained(lowerCamelCase) self.assertIsNotNone(lowerCamelCase) @require_torch @require_sentencepiece @require_tokenizers class _lowerCamelCase( unittest.TestCase ): @unittest.skip(reason='Model not available yet') def UpperCamelCase ( self) -> Tuple: """simple docstring""" pass @slow def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : List[str] = DebertaModel.from_pretrained('microsoft/deberta-base') _lowercase : List[Any] = torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]]) _lowercase : int = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) with torch.no_grad(): _lowercase : List[str] = model(lowerCamelCase, attention_mask=lowerCamelCase)[0] # compare the actual values for a slice. _lowercase : Optional[Any] = torch.tensor( [[[-0.5_9_8_6, -0.8_0_5_5, -0.8_4_6_2], [1.4_4_8_4, -0.9_3_4_8, -0.8_0_5_9], [0.3_1_2_3, 0.0_0_3_2, -1.4_1_3_1]]]) self.assertTrue(torch.allclose(output[:, 1:4, 1:4], lowerCamelCase, atol=1E-4), F'''{output[:, 1:4, 1:4]}''')
21
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class _UpperCamelCase ( pl.LightningModule ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCAmelCase = model __lowerCAmelCase = 2 __lowerCAmelCase = nn.Linear(self.model.config.hidden_size , self.num_labels ) def snake_case ( self ): pass def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = LongformerModel.from_pretrained(_UpperCamelCase ) __lowerCAmelCase = LightningModel(_UpperCamelCase ) __lowerCAmelCase = torch.load(_UpperCamelCase , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model __lowerCAmelCase = LongformerForQuestionAnswering.from_pretrained(_UpperCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(_UpperCamelCase ) print(f"Conversion successful. Model saved under {pytorch_dump_folder_path}" ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--longformer_model", default=None, type=str, required=True, help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.", ) parser.add_argument( "--longformer_question_answering_ckpt_path", default=None, type=str, required=True, help="Path the official PyTorch Lightning Checkpoint.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) A : Optional[int] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
57
0
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class A_ : def __init__( self : str , snake_case_ : int , snake_case_ : Union[str, Any]=2 , snake_case_ : List[Any]=True , snake_case_ : str=False , snake_case_ : str=1_0 , snake_case_ : str=3 , snake_case_ : Dict=3_2 * 4 , snake_case_ : Any=3_2 * 6 , snake_case_ : Optional[Any]=4 , snake_case_ : Optional[int]=3_2 , ): _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = is_training _UpperCAmelCase = use_auxiliary_loss _UpperCAmelCase = num_queries _UpperCAmelCase = num_channels _UpperCAmelCase = min_size _UpperCAmelCase = max_size _UpperCAmelCase = num_labels _UpperCAmelCase = mask_feature_size def lowercase ( self : Union[str, Any] ): _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( snake_case_ ) _UpperCAmelCase = torch.ones([self.batch_size, self.min_size, self.max_size] , device=snake_case_ ) _UpperCAmelCase = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=snake_case_ ) > 0.5 ).float() _UpperCAmelCase = (torch.rand((self.batch_size, self.num_labels) , device=snake_case_ ) > 0.5).long() _UpperCAmelCase = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowercase ( self : List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def lowercase ( self : Optional[Any] ): _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def lowercase ( self : List[Any] , snake_case_ : Optional[Any] , snake_case_ : Optional[Any] ): _UpperCAmelCase = output.encoder_hidden_states _UpperCAmelCase = output.pixel_decoder_hidden_states _UpperCAmelCase = output.transformer_decoder_hidden_states self.parent.assertTrue(len(snake_case_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(snake_case_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(snake_case_ ) , config.decoder_config.decoder_layers ) def lowercase ( self : Tuple , snake_case_ : str , snake_case_ : Optional[int] , snake_case_ : Any , snake_case_ : Optional[Any]=False ): with torch.no_grad(): _UpperCAmelCase = MaskFormerModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() _UpperCAmelCase = model(pixel_values=snake_case_ , pixel_mask=snake_case_ ) _UpperCAmelCase = model(snake_case_ , output_hidden_states=snake_case_ ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(snake_case_ , snake_case_ ) def lowercase ( self : Any , snake_case_ : List[str] , snake_case_ : List[Any] , snake_case_ : int , snake_case_ : str , snake_case_ : List[Any] ): _UpperCAmelCase = MaskFormerForInstanceSegmentation(config=snake_case_ ) model.to(snake_case_ ) model.eval() def comm_check_on_output(snake_case_ : int ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _UpperCAmelCase = model(pixel_values=snake_case_ , pixel_mask=snake_case_ ) _UpperCAmelCase = model(snake_case_ ) comm_check_on_output(snake_case_ ) _UpperCAmelCase = model( pixel_values=snake_case_ , pixel_mask=snake_case_ , mask_labels=snake_case_ , class_labels=snake_case_ ) comm_check_on_output(snake_case_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class A_ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): _lowerCamelCase : Dict = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () _lowerCamelCase : Tuple = ( {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) _lowerCamelCase : Optional[Any] = False _lowerCamelCase : Dict = False _lowerCamelCase : Any = False _lowerCamelCase : List[Any] = False def lowercase ( self : Optional[int] ): _UpperCAmelCase = MaskFormerModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ ) def lowercase ( self : Optional[Any] ): self.config_tester.run_common_tests() def lowercase ( self : Union[str, Any] ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(snake_case_ , **snake_case_ , output_hidden_states=snake_case_ ) def lowercase ( self : int ): _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*snake_case_ ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def lowercase ( self : Any ): pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def lowercase ( self : List[str] ): pass @unittest.skip(reason="MaskFormer is not a generative model" ) def lowercase ( self : List[str] ): pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def lowercase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def lowercase ( self : Any ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def lowercase ( self : Union[str, Any] ): pass def lowercase ( self : List[str] ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(snake_case_ ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case_ ) @slow def lowercase ( self : Optional[int] ): for model_name in ["facebook/maskformer-swin-small-coco"]: _UpperCAmelCase = MaskFormerModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def lowercase ( self : Optional[int] ): _UpperCAmelCase = (self.model_tester.min_size,) * 2 _UpperCAmelCase = { "pixel_values": torch.randn((2, 3, *size) , device=snake_case_ ), "mask_labels": torch.randn((2, 1_0, *size) , device=snake_case_ ), "class_labels": torch.zeros(2 , 1_0 , device=snake_case_ ).long(), } _UpperCAmelCase = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(snake_case_ ) _UpperCAmelCase = model(**snake_case_ ) self.assertTrue(outputs.loss is not None ) def lowercase ( self : Dict ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(snake_case_ , **snake_case_ , output_hidden_states=snake_case_ ) def lowercase ( self : Any ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(snake_case_ ).to(snake_case_ ) _UpperCAmelCase = model(**snake_case_ , output_attentions=snake_case_ ) self.assertTrue(outputs.attentions is not None ) def lowercase ( self : int ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss _UpperCAmelCase = self.all_model_classes[1] _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() _UpperCAmelCase = model_class(snake_case_ ) model.to(snake_case_ ) model.train() _UpperCAmelCase = model(snake_case_ , mask_labels=snake_case_ , class_labels=snake_case_ ).loss loss.backward() def lowercase ( self : int ): # only MaskFormerForInstanceSegmentation has the loss _UpperCAmelCase = self.all_model_classes[1] _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() _UpperCAmelCase = True _UpperCAmelCase = True _UpperCAmelCase = model_class(snake_case_ ) model.to(snake_case_ ) model.train() _UpperCAmelCase = model(snake_case_ , mask_labels=snake_case_ , class_labels=snake_case_ ) _UpperCAmelCase = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _UpperCAmelCase = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't _UpperCAmelCase = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _UpperCAmelCase = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=snake_case_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __SCREAMING_SNAKE_CASE :Dict = 1e-4 def UpperCAmelCase_ ( ) -> List[str]: '''simple docstring''' _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class A_ ( unittest.TestCase ): @cached_property def lowercase ( self : Dict ): return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def lowercase ( self : List[Any] ): _UpperCAmelCase = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(snake_case_ ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(snake_case_ , return_tensors="pt" ).to(snake_case_ ) _UpperCAmelCase = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(snake_case_ , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): _UpperCAmelCase = model(**snake_case_ ) _UpperCAmelCase = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(snake_case_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , snake_case_ , atol=snake_case_ ) ) _UpperCAmelCase = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(snake_case_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , snake_case_ , atol=snake_case_ ) ) _UpperCAmelCase = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(snake_case_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , snake_case_ , atol=snake_case_ ) ) def lowercase ( self : Tuple ): _UpperCAmelCase = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(snake_case_ ) .eval() ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(snake_case_ , return_tensors="pt" ).to(snake_case_ ) _UpperCAmelCase = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(snake_case_ , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): _UpperCAmelCase = model(**snake_case_ ) # masks_queries_logits _UpperCAmelCase = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) _UpperCAmelCase = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] _UpperCAmelCase = torch.tensor(snake_case_ ).to(snake_case_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , snake_case_ , atol=snake_case_ ) ) # class_queries_logits _UpperCAmelCase = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) _UpperCAmelCase = torch.tensor( [ [1.6_512e00, -5.2_572e00, -3.3_519e00], [3.6_169e-02, -5.9_025e00, -2.9_313e00], [1.0_766e-04, -7.7_630e00, -5.1_263e00], ] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , snake_case_ , atol=snake_case_ ) ) def lowercase ( self : int ): _UpperCAmelCase = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(snake_case_ ) .eval() ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(snake_case_ , return_tensors="pt" ).to(snake_case_ ) _UpperCAmelCase = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(snake_case_ , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): _UpperCAmelCase = model(**snake_case_ ) # masks_queries_logits _UpperCAmelCase = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) _UpperCAmelCase = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] _UpperCAmelCase = torch.tensor(snake_case_ ).to(snake_case_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , snake_case_ , atol=snake_case_ ) ) # class_queries_logits _UpperCAmelCase = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) _UpperCAmelCase = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , snake_case_ , atol=snake_case_ ) ) def lowercase ( self : List[Any] ): _UpperCAmelCase = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(snake_case_ ) .eval() ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors="pt" , ) _UpperCAmelCase = inputs["pixel_values"].to(snake_case_ ) _UpperCAmelCase = [el.to(snake_case_ ) for el in inputs["mask_labels"]] _UpperCAmelCase = [el.to(snake_case_ ) for el in inputs["class_labels"]] with torch.no_grad(): _UpperCAmelCase = model(**snake_case_ ) self.assertTrue(outputs.loss is not None )
22
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = False while is_sorted is False: # Until all the indices are traversed keep looping __lowerCAmelCase = True for i in range(0 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False for i in range(1 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False return input_list if __name__ == "__main__": print("Enter list to be sorted") A : Union[str, Any] = [int(x) for x in input().split()] # inputing elements of the list in one line A : str = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
57
0
'''simple docstring''' import math import sys def snake_case_ ( _lowerCAmelCase : str ) -> str: UpperCAmelCase : List[Any] = '''''' try: with open(_lowerCAmelCase , '''rb''' ) as binary_file: UpperCAmelCase : str = binary_file.read() for dat in data: UpperCAmelCase : Optional[int] = f"""{dat:08b}""" result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def snake_case_ ( _lowerCAmelCase : str ) -> str: UpperCAmelCase : Dict = {'''0''': '''0''', '''1''': '''1'''} UpperCAmelCase , UpperCAmelCase : Optional[Any] = '''''', '''''' UpperCAmelCase : int = len(_lowerCAmelCase ) for i in range(len(_lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue UpperCAmelCase : List[Any] = lexicon[curr_string] result += last_match_id UpperCAmelCase : List[str] = last_match_id + '''0''' if math.loga(_lowerCAmelCase ).is_integer(): UpperCAmelCase : List[str] = {} for curr_key in list(_lowerCAmelCase ): UpperCAmelCase : Any = lexicon.pop(_lowerCAmelCase ) UpperCAmelCase : Dict = new_lex UpperCAmelCase : Optional[Any] = last_match_id + '''1''' index += 1 UpperCAmelCase : List[Any] = '''''' return result def snake_case_ ( _lowerCAmelCase : str , _lowerCAmelCase : str ) -> None: UpperCAmelCase : Union[str, Any] = 8 try: with open(_lowerCAmelCase , '''wb''' ) as opened_file: UpperCAmelCase : Optional[int] = [ to_write[i : i + byte_length] for i in range(0 , len(_lowerCAmelCase ) , _lowerCAmelCase ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(_lowerCAmelCase , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def snake_case_ ( _lowerCAmelCase : str ) -> str: UpperCAmelCase : List[Any] = 0 for letter in data_bits: if letter == "1": break counter += 1 UpperCAmelCase : Tuple = data_bits[counter:] UpperCAmelCase : Optional[Any] = data_bits[counter + 1 :] return data_bits def snake_case_ ( _lowerCAmelCase : str , _lowerCAmelCase : str ) -> None: UpperCAmelCase : Optional[Any] = read_file_binary(_lowerCAmelCase ) UpperCAmelCase : Dict = remove_prefix(_lowerCAmelCase ) UpperCAmelCase : Optional[Any] = decompress_data(_lowerCAmelCase ) write_file_binary(_lowerCAmelCase , _lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
23
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =["""image_processor""", """tokenizer"""] __UpperCAmelCase : Optional[Any] ="""CLIPImageProcessor""" __UpperCAmelCase : Union[str, Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): __lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) __lowerCAmelCase = kwargs.pop("feature_extractor" ) __lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self , __a=None , __a=None , __a=None , **__a ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __lowerCAmelCase = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: __lowerCAmelCase = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: __lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): __lowerCAmelCase = self.tokenizer.model_input_names __lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
57
0
def lowerCamelCase__ ( snake_case_ : int = 6008_5147_5143 ) -> int: try: __snake_case = int(snake_case_ ) except (TypeError, ValueError): raise TypeError('''Parameter n must be int or castable to int.''' ) if n <= 0: raise ValueError('''Parameter n must be greater than or equal to one.''' ) __snake_case = 1 __snake_case = 2 while i * i <= n: while n % i == 0: __snake_case = i n //= i i += 1 if n > 1: __snake_case = n return int(snake_case_ ) if __name__ == "__main__": print(F'{solution() = }')
24
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class _UpperCamelCase : '''simple docstring''' pass
57
0
"""simple docstring""" import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin UpperCAmelCase__ : Tuple = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class lowerCAmelCase_ : """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=13 , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=14 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=19 , SCREAMING_SNAKE_CASE__=5 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=[1, 2, 3, 4, 5] , SCREAMING_SNAKE_CASE__=25 , SCREAMING_SNAKE_CASE__=5 , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = d_model SCREAMING_SNAKE_CASE__ : List[str] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = prediction_length SCREAMING_SNAKE_CASE__ : List[str] = context_length SCREAMING_SNAKE_CASE__ : Optional[Any] = cardinality SCREAMING_SNAKE_CASE__ : List[str] = num_time_features SCREAMING_SNAKE_CASE__ : Optional[int] = lags_sequence SCREAMING_SNAKE_CASE__ : Dict = embedding_dimension SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = context_length SCREAMING_SNAKE_CASE__ : Optional[Any] = prediction_length + label_length SCREAMING_SNAKE_CASE__ : List[Any] = label_length SCREAMING_SNAKE_CASE__ : Tuple = moving_average SCREAMING_SNAKE_CASE__ : Union[str, Any] = autocorrelation_factor def __magic_name__ (self ) -> Any: """simple docstring""" return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = config.context_length + max(config.lags_sequence ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) SCREAMING_SNAKE_CASE__ : str = floats_tensor([self.batch_size, _past_length] ) SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, config.prediction_length] ) SCREAMING_SNAKE_CASE__ : str = { """past_values""": past_values, """static_categorical_features""": static_categorical_features, """past_time_features""": past_time_features, """past_observed_mask""": past_observed_mask, """future_time_features""": future_time_features, """future_values""": future_values, } return inputs_dict def __magic_name__ (self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_config() SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_autoformer_inputs_dict(SCREAMING_SNAKE_CASE__ ) return config, inputs_dict def __magic_name__ (self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_config_and_inputs() return config, inputs_dict def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = AutoformerModel(config=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ).eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.encoder_last_hidden_state SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.get_encoder() encoder.save_pretrained(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = AutoformerEncoder.from_pretrained(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = model.create_network_inputs(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) SCREAMING_SNAKE_CASE__ : Tuple = encoder(inputs_embeds=SCREAMING_SNAKE_CASE__ )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) SCREAMING_SNAKE_CASE__ : List[Any] = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) SCREAMING_SNAKE_CASE__ : str = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : List[str] = model.get_decoder() decoder.save_pretrained(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = AutoformerDecoder.from_pretrained(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = decoder( trend=SCREAMING_SNAKE_CASE__ , inputs_embeds=SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class lowerCAmelCase_ (a__ , a__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase : Optional[int] = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () __UpperCamelCase : Optional[int] = (AutoformerForPrediction,) if is_torch_available() else () __UpperCamelCase : int = {'''feature-extraction''': AutoformerModel} if is_torch_available() else {} __UpperCamelCase : Any = False __UpperCamelCase : int = False __UpperCamelCase : str = False __UpperCamelCase : Optional[int] = False __UpperCamelCase : int = False __UpperCamelCase : List[str] = False def __magic_name__ (self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = AutoformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> int: """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ (self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = model_class.from_pretrained(SCREAMING_SNAKE_CASE__ , output_loading_info=SCREAMING_SNAKE_CASE__ ) self.assertEqual(info["""missing_keys"""] , [] ) def __magic_name__ (self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason="""Model has no tokens embeddings""" ) def __magic_name__ (self ) -> List[Any]: """simple docstring""" pass def __magic_name__ (self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = inspect.signature(getattr(SCREAMING_SNAKE_CASE__ , """forward""" ) ) # The main input is the name of the argument after `self` SCREAMING_SNAKE_CASE__ : Dict = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[str] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Any = [ """past_values""", """past_time_features""", """past_observed_mask""", """static_categorical_features""", """static_real_features""", """future_values""", """future_time_features""", ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append("""future_observed_mask""" ) expected_arg_names.extend( [ """decoder_attention_mask""", """head_mask""", """decoder_head_mask""", """cross_attn_head_mask""", """encoder_outputs""", """past_key_values""", """output_hidden_states""", """output_attentions""", """use_cache""", """return_dict""", ] ) self.assertListEqual(arg_names[: len(SCREAMING_SNAKE_CASE__ )] , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[Any] = getattr(self.model_tester , """seq_length""" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = getattr(self.model_tester , """decoder_seq_length""" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(self.model_tester , """encoder_seq_length""" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = getattr(self.model_tester , """d_model""" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(self.model_tester , """num_attention_heads""" , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = d_model // num_attention_heads for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : str = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : List[str] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.encoder_attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = len(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # decoder attentions SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.decoder_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions SCREAMING_SNAKE_CASE__ : List[str] = outputs.cross_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : str = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 2 , len(SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : Any = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def __magic_name__ (self ) -> Dict: """simple docstring""" super().test_retain_grad_hidden_states_attentions() def lowercase_ ( _snake_case="train-batch.pt" ): SCREAMING_SNAKE_CASE__ : List[str] = hf_hub_download(repo_id="""hf-internal-testing/tourism-monthly-batch""" ,filename=_snake_case ,repo_type="""dataset""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.load(_snake_case ,map_location=_snake_case ) return batch @require_torch @slow class lowerCAmelCase_ (unittest.TestCase ): """simple docstring""" def __magic_name__ (self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoformerModel.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = prepare_batch() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model( past_values=batch["""past_values"""] , past_time_features=batch["""past_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , static_categorical_features=batch["""static_categorical_features"""] , future_values=batch["""future_values"""] , future_time_features=batch["""future_time_features"""] , )[0] SCREAMING_SNAKE_CASE__ : int = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=SCREAMING_SNAKE_CASE__ ) ) def __magic_name__ (self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = prepare_batch("""val-batch.pt""" ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model( past_values=batch["""past_values"""] , past_time_features=batch["""past_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , static_categorical_features=batch["""static_categorical_features"""] , ).encoder_last_hidden_state SCREAMING_SNAKE_CASE__ : Dict = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=SCREAMING_SNAKE_CASE__ ) ) def __magic_name__ (self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prepare_batch("""val-batch.pt""" ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model.generate( static_categorical_features=batch["""static_categorical_features"""] , past_time_features=batch["""past_time_features"""] , past_values=batch["""past_values"""] , future_time_features=batch["""future_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , ) SCREAMING_SNAKE_CASE__ : List[str] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , SCREAMING_SNAKE_CASE__ , rtol=1E-1 ) )
25
"""simple docstring""" import sys from collections import defaultdict class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): return self.node_position[vertex] def snake_case ( self , __a , __a ): __lowerCAmelCase = pos def snake_case ( self , __a , __a , __a , __a ): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCAmelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCAmelCase = 2 * start + 1 else: __lowerCAmelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCAmelCase , __lowerCAmelCase = heap[smallest_child], positions[smallest_child] __lowerCAmelCase , __lowerCAmelCase = ( heap[start], positions[start], ) __lowerCAmelCase , __lowerCAmelCase = temp, tempa __lowerCAmelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __a ) self.top_to_bottom(__a , __a , __a , __a ) def snake_case ( self , __a , __a , __a , __a ): __lowerCAmelCase = position[index] while index != 0: __lowerCAmelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCAmelCase = heap[parent] __lowerCAmelCase = position[parent] self.set_position(position[parent] , __a ) else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , __a ) break __lowerCAmelCase = parent else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , 0 ) def snake_case ( self , __a , __a ): __lowerCAmelCase = len(__a ) // 2 - 1 for i in range(__a , -1 , -1 ): self.top_to_bottom(__a , __a , len(__a ) , __a ) def snake_case ( self , __a , __a ): __lowerCAmelCase = positions[0] __lowerCAmelCase = sys.maxsize self.top_to_bottom(__a , 0 , len(__a ) , __a ) return temp def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = Heap() __lowerCAmelCase = [0] * len(_UpperCamelCase ) __lowerCAmelCase = [-1] * len(_UpperCamelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCAmelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCAmelCase = [] for vertex in range(len(_UpperCamelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_UpperCamelCase ) heap.node_position.append(_UpperCamelCase ) __lowerCAmelCase = [] __lowerCAmelCase = 1 __lowerCAmelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCAmelCase = 0 __lowerCAmelCase = distance heap.heapify(_UpperCamelCase , _UpperCamelCase ) for _ in range(1 , len(_UpperCamelCase ) ): __lowerCAmelCase = heap.delete_minimum(_UpperCamelCase , _UpperCamelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCAmelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_UpperCamelCase )] ): __lowerCAmelCase = distance heap.bottom_to_top( _UpperCamelCase , heap.get_position(_UpperCamelCase ) , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A : Optional[Any] = int(input("Enter number of edges: ").strip()) A : Dict = defaultdict(list) for _ in range(edges_number): A : str = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
57
0
import argparse import json from tqdm import tqdm def lowerCAmelCase_ ( ): _A : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--src_path""",type=snake_case_,default="""biencoder-nq-dev.json""",help="""Path to raw DPR training data""",) parser.add_argument( """--evaluation_set""",type=snake_case_,help="""where to store parsed evaluation_set file""",) parser.add_argument( """--gold_data_path""",type=snake_case_,help="""where to store parsed gold_data_path file""",) _A : str = parser.parse_args() with open(args.src_path,"""r""" ) as src_file, open(args.evaluation_set,"""w""" ) as eval_file, open( args.gold_data_path,"""w""" ) as gold_file: _A : List[Any] = json.load(snake_case_ ) for dpr_record in tqdm(snake_case_ ): _A : Union[str, Any] = dpr_record["""question"""] _A : List[str] = [context["""title"""] for context in dpr_record["""positive_ctxs"""]] eval_file.write(question + """\n""" ) gold_file.write("""\t""".join(snake_case_ ) + """\n""" ) if __name__ == "__main__": main()
26
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() A : Tuple = logging.get_logger(__name__) A : Tuple = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] A : Optional[Any] = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = torch.load(_UpperCamelCase , map_location="cpu" ) return sd def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=rename_keys_prefix ): '''simple docstring''' __lowerCAmelCase = OrderedDict() __lowerCAmelCase = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __lowerCAmelCase = key for name_pair in rename_keys_prefix: __lowerCAmelCase = new_key.replace(name_pair[0] , name_pair[1] ) __lowerCAmelCase = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __lowerCAmelCase = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}." # Get Config if "pre" in checkpoint_path: __lowerCAmelCase = "pretraining" if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 1024} else: raise NotImplementedError(f"No implementation found for `{checkpoint_path}`." ) else: if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} __lowerCAmelCase = "multichoice" elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} __lowerCAmelCase = "vqa_advanced" elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048, "num_labels": 3129} __lowerCAmelCase = "vqa" elif "nlvr" in checkpoint_path: __lowerCAmelCase = { "visual_embedding_dim": 1024, "num_labels": 2, } __lowerCAmelCase = "nlvr" __lowerCAmelCase = VisualBertConfig(**_UpperCamelCase ) # Load State Dict __lowerCAmelCase = load_state_dict(_UpperCamelCase ) __lowerCAmelCase = get_new_dict(_UpperCamelCase , _UpperCamelCase ) if model_type == "pretraining": __lowerCAmelCase = VisualBertForPreTraining(_UpperCamelCase ) elif model_type == "vqa": __lowerCAmelCase = VisualBertForQuestionAnswering(_UpperCamelCase ) elif model_type == "nlvr": __lowerCAmelCase = VisualBertForVisualReasoning(_UpperCamelCase ) elif model_type == "multichoice": __lowerCAmelCase = VisualBertForMultipleChoice(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Save Checkpoints Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") A : Optional[int] = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
57
0
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip __lowercase : Dict = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : List[Any] ): return max(metric_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for gt in ground_truths ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[str] ): __a : List[Any] = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , 'r' ).readlines()] __a : List[Any] = [] if args.gold_data_mode == "qa": __a : Any = pd.read_csv(_SCREAMING_SNAKE_CASE , sep='\t' , header=_SCREAMING_SNAKE_CASE ) for answer_list in data[1]: __a : Union[str, Any] = ast.literal_eval(_SCREAMING_SNAKE_CASE ) answers.append(_SCREAMING_SNAKE_CASE ) else: __a : Optional[int] = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , 'r' ).readlines()] __a : Optional[int] = [[reference] for reference in references] __a : List[Any] = 0 for prediction, ground_truths in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): total += 1 em += metric_max_over_ground_truths(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) fa += metric_max_over_ground_truths(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __a : Tuple = 1_0_0.0 * em / total __a : Any = 1_0_0.0 * fa / total logger.info(F"""F1: {fa:.2f}""" ) logger.info(F"""EM: {em:.2f}""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : str = args.k __a : Union[str, Any] = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , 'r' ).readlines()] __a : Tuple = [line.strip() for line in open(_SCREAMING_SNAKE_CASE , 'r' ).readlines()] __a : Optional[int] = 0 for hypo, reference in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __a : Optional[Any] = set(hypo.split('\t' )[:k] ) __a : Union[str, Any] = set(reference.split('\t' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k __a : Tuple = 1_0_0.0 * em / total logger.info(F"""Precision@{k}: {em: .2f}""" ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[int] ): def strip_title(_SCREAMING_SNAKE_CASE : int ): if title.startswith('"' ): __a : int = title[1:] if title.endswith('"' ): __a : Union[str, Any] = title[:-1] return title __a : str = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _SCREAMING_SNAKE_CASE , return_tensors='pt' , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , )['input_ids'].to(args.device ) __a : Tuple = rag_model.rag.question_encoder(_SCREAMING_SNAKE_CASE ) __a : Tuple = question_enc_outputs[0] __a : int = rag_model.retriever( _SCREAMING_SNAKE_CASE , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='pt' , ) __a : Tuple = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) __a : Tuple = [] for docs in all_docs: __a : Dict = [strip_title(_SCREAMING_SNAKE_CASE ) for title in docs['title']] provenance_strings.append('\t'.join(_SCREAMING_SNAKE_CASE ) ) return provenance_strings def lowerCamelCase (_SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Any ): with torch.no_grad(): __a : Dict = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _SCREAMING_SNAKE_CASE , return_tensors='pt' , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = inputs_dict.input_ids.to(args.device ) __a : str = inputs_dict.attention_mask.to(args.device ) __a : Dict = rag_model.generate( # rag_model overwrites generate _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=_SCREAMING_SNAKE_CASE , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) __a : Optional[Any] = rag_model.retriever.generator_tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) if args.print_predictions: for q, a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): logger.info('Q: {} - A: {}'.format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) return answers def lowerCamelCase (): __a : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '--model_type' , choices=['rag_sequence', 'rag_token', 'bart'] , type=_SCREAMING_SNAKE_CASE , help=( 'RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the' ' model_name_or_path' ) , ) parser.add_argument( '--index_name' , default=_SCREAMING_SNAKE_CASE , choices=['exact', 'compressed', 'legacy'] , type=_SCREAMING_SNAKE_CASE , help='RAG model retriever type' , ) parser.add_argument( '--index_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Path to the retrieval index' , ) parser.add_argument('--n_docs' , default=5 , type=_SCREAMING_SNAKE_CASE , help='Number of retrieved docs' ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained checkpoints or model identifier from huggingface.co/models' , ) parser.add_argument( '--eval_mode' , choices=['e2e', 'retrieval'] , default='e2e' , type=_SCREAMING_SNAKE_CASE , help=( 'Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates' ' precision@k.' ) , ) parser.add_argument('--k' , default=1 , type=_SCREAMING_SNAKE_CASE , help='k for the precision@k calculation' ) parser.add_argument( '--evaluation_set' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to a file containing evaluation samples' , ) parser.add_argument( '--gold_data_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to a tab-separated file with gold samples' , ) parser.add_argument( '--gold_data_mode' , default='qa' , type=_SCREAMING_SNAKE_CASE , choices=['qa', 'ans'] , help=( 'Format of the gold data file' 'qa - a single line in the following format: question [tab] answer_list' 'ans - a single line of the gold file contains the expected answer string' ) , ) parser.add_argument( '--predictions_path' , type=_SCREAMING_SNAKE_CASE , default='predictions.txt' , help='Name of the predictions file, to be stored in the checkpoints directory' , ) parser.add_argument( '--eval_all_checkpoints' , action='store_true' , help='Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number' , ) parser.add_argument( '--eval_batch_size' , default=8 , type=_SCREAMING_SNAKE_CASE , help='Batch size per GPU/CPU for evaluation.' , ) parser.add_argument( '--recalculate' , help='Recalculate predictions even if the prediction file exists' , action='store_true' , ) parser.add_argument( '--num_beams' , default=4 , type=_SCREAMING_SNAKE_CASE , help='Number of beams to be used when generating answers' , ) parser.add_argument('--min_length' , default=1 , type=_SCREAMING_SNAKE_CASE , help='Min length of the generated answers' ) parser.add_argument('--max_length' , default=50 , type=_SCREAMING_SNAKE_CASE , help='Max length of the generated answers' ) parser.add_argument( '--print_predictions' , action='store_true' , help='If True, prints predictions while evaluating.' , ) parser.add_argument( '--print_docs' , action='store_true' , help='If True, prints docs retried while generating.' , ) __a : Dict = parser.parse_args() __a : Dict = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) return args def lowerCamelCase (_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Tuple = {} if args.model_type is None: __a : str = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('rag' ): __a : int = RagTokenForGeneration if args.model_type == 'rag_token' else RagSequenceForGeneration __a : int = args.n_docs if args.index_name is not None: __a : Optional[Any] = args.index_name if args.index_path is not None: __a : List[str] = args.index_path else: __a : Tuple = BartForConditionalGeneration __a : int = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('Evaluate the following checkpoints: %s' , _SCREAMING_SNAKE_CASE ) __a : str = get_scores if args.eval_mode == 'e2e' else get_precision_at_k __a : Optional[int] = evaluate_batch_eae if args.eval_mode == 'e2e' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('Calculating metrics based on an existing predictions file: {}'.format(args.predictions_path ) ) score_fn(_SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) continue logger.info('***** Running evaluation for {} *****'.format(_SCREAMING_SNAKE_CASE ) ) logger.info(' Batch size = %d' , args.eval_batch_size ) logger.info(' Predictions will be stored under {}'.format(args.predictions_path ) ) if args.model_type.startswith('rag' ): __a : Tuple = RagRetriever.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __a : Union[str, Any] = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , retriever=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) model.retriever.init_retrieval() else: __a : Union[str, Any] = model_class.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) model.to(args.device ) with open(args.evaluation_set , 'r' ) as eval_file, open(args.predictions_path , 'w' ) as preds_file: __a : Tuple = [] for line in tqdm(_SCREAMING_SNAKE_CASE ): questions.append(line.strip() ) if len(_SCREAMING_SNAKE_CASE ) == args.eval_batch_size: __a : List[Any] = evaluate_batch_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) preds_file.write('\n'.join(_SCREAMING_SNAKE_CASE ) + '\n' ) preds_file.flush() __a : Dict = [] if len(_SCREAMING_SNAKE_CASE ) > 0: __a : Dict = evaluate_batch_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) preds_file.write('\n'.join(_SCREAMING_SNAKE_CASE ) ) preds_file.flush() score_fn(_SCREAMING_SNAKE_CASE , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": __lowercase : Optional[Any] = get_args() main(args)
27
"""simple docstring""" class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [ [], [], [], ] def snake_case ( self , __a , __a ): try: if len(self.queues[priority] ) >= 1_00: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(__a ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def snake_case ( self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues ) ) class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): if len(self.queue ) == 1_00: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(__a ) def snake_case ( self ): if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(__a ) return data def __str__( self ): return str(self.queue ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
57
0
'''simple docstring''' def __lowerCamelCase ( ) -> Dict: """simple docstring""" UpperCamelCase = 0 for i in range(1 , 1_001 ): total += i**i return str(A__ )[-10:] if __name__ == "__main__": print(solution())
28
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' 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\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) __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()
57
0
import math import random def lowercase__ ( __snake_case : float , __snake_case : bool = False ): '''simple docstring''' if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value __UpperCAmelCase = 0.0_2 def lowercase__ ( __snake_case : int , __snake_case : int ): '''simple docstring''' UpperCAmelCase_ : str = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(__snake_case ): # Forward propagation UpperCAmelCase_ : str = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? UpperCAmelCase_ : Union[str, Any] = (expected / 100) - layer_a # Error delta UpperCAmelCase_ : Any = layer_1_error * sigmoid_function(__snake_case , __snake_case ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = int(input('Expected value: ')) __UpperCAmelCase = int(input('Number of propagations: ')) print(forward_propagation(expected, number_propagations))
29
"""simple docstring""" def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = 1 while len(_UpperCamelCase ) < 1e6: constant.append(str(_UpperCamelCase ) ) i += 1 __lowerCAmelCase = "".join(_UpperCamelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
57
0
def a ( snake_case__: list[int] , snake_case__: str ): '''simple docstring''' lowercase_ = int(snake_case__ ) # Initialize Result lowercase_ = [] # Traverse through all denomination for denomination in reversed(snake_case__ ): # Find denominations while int(snake_case__ ) >= int(snake_case__ ): total_value -= int(snake_case__ ) answer.append(snake_case__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": __a = [] __a = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): __a = 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())) __a = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter __a = [1, 2, 5, 1_0, 2_0, 5_0, 1_0_0, 5_0_0, 2_0_0_0] __a = 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}: ") __a = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
30
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs A : Union[str, Any] = imread(R"digital_image_processing/image_data/lena_small.jpg") A : Optional[Any] = cvtColor(img, COLOR_BGR2GRAY) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = cn.convert_to_negative(_UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def _lowerCamelCase ( ): '''simple docstring''' with Image.open("digital_image_processing/image_data/lena_small.jpg" ) as img: # Work around assertion for response assert str(cc.change_contrast(_UpperCamelCase , 110 ) ).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = imread("digital_image_processing/image_data/lena_small.jpg" , 0 ) # assert ambiguous array for all == True assert canny_img.all() __lowerCAmelCase = canny.canny(_UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def _lowerCamelCase ( ): '''simple docstring''' assert gg.gaussian_filter(_UpperCamelCase , 5 , sigma=0.9 ).all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __lowerCAmelCase = conv.img_convolve(_UpperCamelCase , _UpperCamelCase ).astype(_UpperCamelCase ) assert res.any() def _lowerCamelCase ( ): '''simple docstring''' assert med.median_filter(_UpperCamelCase , 3 ).any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase = sob.sobel_filter(_UpperCamelCase ) assert grad.any() and theta.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = sp.make_sepia(_UpperCamelCase , 20 ) assert sepia.all() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' __lowerCAmelCase = bs.Burkes(imread(_UpperCamelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' __lowerCAmelCase = rs.NearestNeighbour(imread(_UpperCamelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. __lowerCAmelCase = imread(_UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = image[x_coordinate][y_coordinate] __lowerCAmelCase = lbp.get_neighbors_pixel( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __lowerCAmelCase = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __lowerCAmelCase = lbp.local_binary_value(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert lbp_image.any()
57
0
'''simple docstring''' def UpperCamelCase_ ( _UpperCAmelCase : list ) -> list: """simple docstring""" _UpperCAmelCase : List[Any] = len(_UpperCAmelCase ) for _ in range(_UpperCAmelCase ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: _UpperCAmelCase , _UpperCAmelCase : int = arr[i + 1], arr[i] return arr if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Optional[Any] = list(range(10, 0, -1)) print(F'Original: {arr}. Sorted: {odd_even_transposition(arr)}')
31
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : Optional[int] = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltCLIPTextConfig", "AltCLIPVisionConfig", ], "processing_altclip": ["AltCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = [ "ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "AltCLIPPreTrainedModel", "AltCLIPModel", "AltCLIPTextModel", "AltCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys A : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
import argparse import struct import unittest class SCREAMING_SNAKE_CASE__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : bytes ) -> None: a_ : Tuple = data # Initialize hash values a_ : Tuple = [ 0X6a09_e667, 0Xbb67_ae85, 0X3c6e_f372, 0Xa54f_f53a, 0X510e_527f, 0X9b05_688c, 0X1f83_d9ab, 0X5be0_cd19, ] # Initialize round constants a_ : Tuple = [ 0X428a_2f98, 0X7137_4491, 0Xb5c0_fbcf, 0Xe9b5_dba5, 0X3956_c25b, 0X59f1_11f1, 0X923f_82a4, 0Xab1c_5ed5, 0Xd807_aa98, 0X1283_5b01, 0X2431_85be, 0X550c_7dc3, 0X72be_5d74, 0X80de_b1fe, 0X9bdc_06a7, 0Xc19b_f174, 0Xe49b_69c1, 0Xefbe_4786, 0X0fc1_9dc6, 0X240c_a1cc, 0X2de9_2c6f, 0X4a74_84aa, 0X5cb0_a9dc, 0X76f9_88da, 0X983e_5152, 0Xa831_c66d, 0Xb003_27c8, 0Xbf59_7fc7, 0Xc6e0_0bf3, 0Xd5a7_9147, 0X06ca_6351, 0X1429_2967, 0X27b7_0a85, 0X2e1b_2138, 0X4d2c_6dfc, 0X5338_0d13, 0X650a_7354, 0X766a_0abb, 0X81c2_c92e, 0X9272_2c85, 0Xa2bf_e8a1, 0Xa81a_664b, 0Xc24b_8b70, 0Xc76c_51a3, 0Xd192_e819, 0Xd699_0624, 0Xf40e_3585, 0X106a_a070, 0X19a4_c116, 0X1e37_6c08, 0X2748_774c, 0X34b0_bcb5, 0X391c_0cb3, 0X4ed8_aa4a, 0X5b9c_ca4f, 0X682e_6ff3, 0X748f_82ee, 0X78a5_636f, 0X84c8_7814, 0X8cc7_0208, 0X90be_fffa, 0Xa450_6ceb, 0Xbef9_a3f7, 0Xc671_78f2, ] a_ : int = self.preprocessing(self.data ) self.final_hash() @staticmethod def SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE__ : bytes ) -> bytes: a_ : Any = b'\x80' + (b'\x00' * (6_3 - (len(SCREAMING_SNAKE_CASE__ ) + 8) % 6_4)) a_ : List[str] = struct.pack('>Q' , (len(SCREAMING_SNAKE_CASE__ ) * 8) ) return data + padding + big_endian_integer def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> None: # Convert into blocks of 64 bytes a_ : int = [ self.preprocessed_data[x : x + 6_4] for x in range(0 , len(self.preprocessed_data ) , 6_4 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers a_ : List[str] = list(struct.unpack('>16L' , SCREAMING_SNAKE_CASE__ ) ) # add 48 0-ed integers words += [0] * 4_8 a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ : Tuple = self.hashes for index in range(0 , 6_4 ): if index > 1_5: # modify the zero-ed indexes at the end of the array a_ : Optional[int] = ( self.ror(words[index - 1_5] , 7 ) ^ self.ror(words[index - 1_5] , 1_8 ) ^ (words[index - 1_5] >> 3) ) a_ : List[str] = ( self.ror(words[index - 2] , 1_7 ) ^ self.ror(words[index - 2] , 1_9 ) ^ (words[index - 2] >> 1_0) ) a_ : Union[str, Any] = ( words[index - 1_6] + sa + words[index - 7] + sa ) % 0X1_0000_0000 # Compression a_ : Any = self.ror(SCREAMING_SNAKE_CASE__ , 6 ) ^ self.ror(SCREAMING_SNAKE_CASE__ , 1_1 ) ^ self.ror(SCREAMING_SNAKE_CASE__ , 2_5 ) a_ : List[str] = (e & f) ^ ((~e & 0Xffff_ffff) & g) a_ : Tuple = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0000_0000 a_ : int = self.ror(SCREAMING_SNAKE_CASE__ , 2 ) ^ self.ror(SCREAMING_SNAKE_CASE__ , 1_3 ) ^ self.ror(SCREAMING_SNAKE_CASE__ , 2_2 ) a_ : Optional[Any] = (a & b) ^ (a & c) ^ (b & c) a_ : Tuple = (sa + maj) % 0X1_0000_0000 a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ : List[str] = ( g, f, e, ((d + tempa) % 0X1_0000_0000), c, b, a, ((tempa + tempa) % 0X1_0000_0000), ) a_ : Tuple = [a, b, c, d, e, f, g, h] # Modify final values a_ : Dict = [ ((element + mutated_hash_values[index]) % 0X1_0000_0000) for index, element in enumerate(self.hashes ) ] a_ : Any = ''.join([hex(SCREAMING_SNAKE_CASE__ )[2:].zfill(8 ) for value in self.hashes] ) def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: return 0Xffff_ffff & (value << (3_2 - rotations)) | (value >> rotations) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> None: import hashlib a_ : Union[str, Any] = bytes('Test String' , 'utf-8' ) self.assertEqual(SHAaaa(SCREAMING_SNAKE_CASE__ ).hash , hashlib.shaaaa(SCREAMING_SNAKE_CASE__ ).hexdigest() ) def SCREAMING_SNAKE_CASE_ ( ) -> None: """simple docstring""" import doctest doctest.testmod() a_ : Dict = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) a_ : Optional[int] = parser.parse_args() a_ : List[Any] = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: a_ : Optional[Any] = f.read() else: a_ : Optional[Any] = bytes(__A , 'utf-8' ) print(SHAaaa(__A ).hash ) if __name__ == "__main__": main()
32
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A : Dict = logging.getLogger(__name__) @dataclass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[float] =field( default=0.0 ,metadata={"""help""": """The label smoothing epsilon to apply (if not zero)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """Whether to SortishSamler or not."""} ) __UpperCAmelCase : bool =field( default=lowerCAmelCase__ ,metadata={"""help""": """Whether to use generate to calculate generative metrics (ROUGE, BLEU)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """whether to use adafactor"""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Encoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Decoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field(default=lowerCAmelCase__ ,metadata={"""help""": """Dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Attention dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[str] =field( default="""linear""" ,metadata={"""help""": F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} ,)
57
0
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
33
"""simple docstring""" import argparse import os import re import packaging.version A : Any = "examples/" A : Optional[Any] = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } A : Optional[int] = { "init": "src/transformers/__init__.py", "setup": "setup.py", } A : List[Any] = "README.md" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , _UpperCamelCase ) __lowerCAmelCase = re_pattern.sub(_UpperCamelCase , _UpperCamelCase ) with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for folder, directories, fnames in os.walk(_UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase , pattern="examples" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if not patch: update_version_in_examples(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(_UpperCamelCase ).groups()[0] return packaging.version.parse(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase=False ): '''simple docstring''' __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __lowerCAmelCase = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(f"Which version are you releasing? [{default_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = default_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase , patch=_UpperCamelCase ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = get_version() __lowerCAmelCase = f"{current_version.major}.{current_version.minor + 1}.0.dev0" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(f"Which version are we developing now? [{dev_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = dev_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") A : Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
57
0
'''simple docstring''' import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A =logging.get_logger(__name__) A ={ 'b0': efficientnet.EfficientNetBa, 'b1': efficientnet.EfficientNetBa, 'b2': efficientnet.EfficientNetBa, 'b3': efficientnet.EfficientNetBa, 'b4': efficientnet.EfficientNetBa, 'b5': efficientnet.EfficientNetBa, 'b6': efficientnet.EfficientNetBa, 'b7': efficientnet.EfficientNetBa, } A ={ 'b0': { 'hidden_dim': 12_80, 'width_coef': 1.0, 'depth_coef': 1.0, 'image_size': 2_24, 'dropout_rate': 0.2, 'dw_padding': [], }, 'b1': { 'hidden_dim': 12_80, 'width_coef': 1.0, 'depth_coef': 1.1, 'image_size': 2_40, 'dropout_rate': 0.2, 'dw_padding': [16], }, 'b2': { 'hidden_dim': 14_08, 'width_coef': 1.1, 'depth_coef': 1.2, 'image_size': 2_60, 'dropout_rate': 0.3, 'dw_padding': [5, 8, 16], }, 'b3': { 'hidden_dim': 15_36, 'width_coef': 1.2, 'depth_coef': 1.4, 'image_size': 3_00, 'dropout_rate': 0.3, 'dw_padding': [5, 18], }, 'b4': { 'hidden_dim': 17_92, 'width_coef': 1.4, 'depth_coef': 1.8, 'image_size': 3_80, 'dropout_rate': 0.4, 'dw_padding': [6], }, 'b5': { 'hidden_dim': 20_48, 'width_coef': 1.6, 'depth_coef': 2.2, 'image_size': 4_56, 'dropout_rate': 0.4, 'dw_padding': [13, 27], }, 'b6': { 'hidden_dim': 23_04, 'width_coef': 1.8, 'depth_coef': 2.6, 'image_size': 5_28, 'dropout_rate': 0.5, 'dw_padding': [31], }, 'b7': { 'hidden_dim': 25_60, 'width_coef': 2.0, 'depth_coef': 3.1, 'image_size': 6_00, 'dropout_rate': 0.5, 'dw_padding': [18], }, } def snake_case_ (_a : List[str] ): UpperCAmelCase = EfficientNetConfig() UpperCAmelCase = CONFIG_MAP[model_name]['''hidden_dim'''] UpperCAmelCase = CONFIG_MAP[model_name]['''width_coef'''] UpperCAmelCase = CONFIG_MAP[model_name]['''depth_coef'''] UpperCAmelCase = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase = CONFIG_MAP[model_name]['''dropout_rate'''] UpperCAmelCase = CONFIG_MAP[model_name]['''dw_padding'''] UpperCAmelCase = '''huggingface/label-files''' UpperCAmelCase = '''imagenet-1k-id2label.json''' UpperCAmelCase = 1_0_0_0 UpperCAmelCase = json.load(open(hf_hub_download(_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()} return config def snake_case_ (): UpperCAmelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase = Image.open(requests.get(_a , stream=_a ).raw ) return im def snake_case_ (_a : str ): UpperCAmelCase = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase = EfficientNetImageProcessor( size={'''height''': size, '''width''': size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.4785_3944, 0.473_2864, 0.4743_4163] , do_center_crop=_a , ) return preprocessor def snake_case_ (_a : Optional[Any] ): UpperCAmelCase = [v.split('''_''' )[0].split('''block''' )[1] for v in original_param_names if v.startswith('''block''' )] UpperCAmelCase = sorted(set(_a ) ) UpperCAmelCase = len(_a ) UpperCAmelCase = {b: str(_a ) for b, i in zip(_a , range(_a ) )} UpperCAmelCase = [] rename_keys.append(('''stem_conv/kernel:0''', '''embeddings.convolution.weight''') ) rename_keys.append(('''stem_bn/gamma:0''', '''embeddings.batchnorm.weight''') ) rename_keys.append(('''stem_bn/beta:0''', '''embeddings.batchnorm.bias''') ) rename_keys.append(('''stem_bn/moving_mean:0''', '''embeddings.batchnorm.running_mean''') ) rename_keys.append(('''stem_bn/moving_variance:0''', '''embeddings.batchnorm.running_var''') ) for b in block_names: UpperCAmelCase = block_name_mapping[b] rename_keys.append((F"block{b}_expand_conv/kernel:0", F"encoder.blocks.{hf_b}.expansion.expand_conv.weight") ) rename_keys.append((F"block{b}_expand_bn/gamma:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.weight") ) rename_keys.append((F"block{b}_expand_bn/beta:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.bias") ) rename_keys.append( (F"block{b}_expand_bn/moving_mean:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean") ) rename_keys.append( (F"block{b}_expand_bn/moving_variance:0", F"encoder.blocks.{hf_b}.expansion.expand_bn.running_var") ) rename_keys.append( (F"block{b}_dwconv/depthwise_kernel:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight") ) rename_keys.append((F"block{b}_bn/gamma:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight") ) rename_keys.append((F"block{b}_bn/beta:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias") ) rename_keys.append( (F"block{b}_bn/moving_mean:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean") ) rename_keys.append( (F"block{b}_bn/moving_variance:0", F"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var") ) rename_keys.append((F"block{b}_se_reduce/kernel:0", F"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight") ) rename_keys.append((F"block{b}_se_reduce/bias:0", F"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias") ) rename_keys.append((F"block{b}_se_expand/kernel:0", F"encoder.blocks.{hf_b}.squeeze_excite.expand.weight") ) rename_keys.append((F"block{b}_se_expand/bias:0", F"encoder.blocks.{hf_b}.squeeze_excite.expand.bias") ) rename_keys.append( (F"block{b}_project_conv/kernel:0", F"encoder.blocks.{hf_b}.projection.project_conv.weight") ) rename_keys.append((F"block{b}_project_bn/gamma:0", F"encoder.blocks.{hf_b}.projection.project_bn.weight") ) rename_keys.append((F"block{b}_project_bn/beta:0", F"encoder.blocks.{hf_b}.projection.project_bn.bias") ) rename_keys.append( (F"block{b}_project_bn/moving_mean:0", F"encoder.blocks.{hf_b}.projection.project_bn.running_mean") ) rename_keys.append( (F"block{b}_project_bn/moving_variance:0", F"encoder.blocks.{hf_b}.projection.project_bn.running_var") ) rename_keys.append(('''top_conv/kernel:0''', '''encoder.top_conv.weight''') ) rename_keys.append(('''top_bn/gamma:0''', '''encoder.top_bn.weight''') ) rename_keys.append(('''top_bn/beta:0''', '''encoder.top_bn.bias''') ) rename_keys.append(('''top_bn/moving_mean:0''', '''encoder.top_bn.running_mean''') ) rename_keys.append(('''top_bn/moving_variance:0''', '''encoder.top_bn.running_var''') ) UpperCAmelCase = {} for item in rename_keys: if item[0] in original_param_names: UpperCAmelCase = '''efficientnet.''' + item[1] UpperCAmelCase = '''classifier.weight''' UpperCAmelCase = '''classifier.bias''' return key_mapping def snake_case_ (_a : Dict , _a : List[str] , _a : Dict ): for key, value in tf_params.items(): if "normalization" in key: continue UpperCAmelCase = key_mapping[key] if "_conv" in key and "kernel" in key: UpperCAmelCase = torch.from_numpy(_a ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: UpperCAmelCase = torch.from_numpy(_a ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: UpperCAmelCase = torch.from_numpy(np.transpose(_a ) ) else: UpperCAmelCase = torch.from_numpy(_a ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(_a ) @torch.no_grad() def snake_case_ (_a : Optional[Any] , _a : List[str] , _a : Optional[int] , _a : Dict ): UpperCAmelCase = model_classes[model_name]( include_top=_a , weights='''imagenet''' , input_tensor=_a , input_shape=_a , pooling=_a , classes=1_0_0_0 , classifier_activation='''softmax''' , ) UpperCAmelCase = original_model.trainable_variables UpperCAmelCase = original_model.non_trainable_variables UpperCAmelCase = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: UpperCAmelCase = param.numpy() UpperCAmelCase = list(tf_params.keys() ) # Load HuggingFace model UpperCAmelCase = get_efficientnet_config(_a ) UpperCAmelCase = EfficientNetForImageClassification(_a ).eval() UpperCAmelCase = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('''Converting parameters...''' ) UpperCAmelCase = rename_keys(_a ) replace_params(_a , _a , _a ) # Initialize preprocessor and preprocess input image UpperCAmelCase = convert_image_processor(_a ) UpperCAmelCase = preprocessor(images=prepare_img() , return_tensors='''pt''' ) # HF model inference hf_model.eval() with torch.no_grad(): UpperCAmelCase = hf_model(**_a ) UpperCAmelCase = outputs.logits.detach().numpy() # Original model inference UpperCAmelCase = False UpperCAmelCase = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) UpperCAmelCase = image.img_to_array(_a ) UpperCAmelCase = np.expand_dims(_a , axis=0 ) UpperCAmelCase = original_model.predict(_a ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(_a , _a , atol=1E-3 ), "The predicted logits are not the same." print('''Model outputs match!''' ) if save_model: # Create folder to save model if not os.path.isdir(_a ): os.mkdir(_a ) # Save converted model and image processor hf_model.save_pretrained(_a ) preprocessor.save_pretrained(_a ) if push_to_hub: # Push model and image processor to hub print(F"Pushing converted {model_name} to the hub..." ) UpperCAmelCase = F"efficientnet-{model_name}" preprocessor.push_to_hub(_a ) hf_model.push_to_hub(_a ) if __name__ == "__main__": A =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='b0', type=str, help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].', ) parser.add_argument( '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--save_model', action='store_true', help='Save model to local') parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') A =parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
34
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A : Tuple = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Dict = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : str = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys A : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = CustomTokenizer pass
35
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase = 6008_5147_5143 ): '''simple docstring''' try: __lowerCAmelCase = int(_UpperCamelCase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) __lowerCAmelCase = 2 __lowerCAmelCase = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 __lowerCAmelCase = i while n % i == 0: __lowerCAmelCase = n // i i += 1 return int(_UpperCamelCase ) if __name__ == "__main__": print(f'''{solution() = }''')
57
0
import math import unittest def A ( _lowerCamelCase ): '''simple docstring''' assert isinstance(_lowerCamelCase , _lowerCamelCase ) and ( number >= 0 ), "'number' must been an int and positive" 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(_lowerCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class UpperCAmelCase_ ( unittest.TestCase): def snake_case__ ( self): '''simple docstring''' self.assertTrue(is_prime(2)) self.assertTrue(is_prime(3)) self.assertTrue(is_prime(5)) self.assertTrue(is_prime(7)) self.assertTrue(is_prime(11)) self.assertTrue(is_prime(13)) self.assertTrue(is_prime(17)) self.assertTrue(is_prime(19)) self.assertTrue(is_prime(23)) self.assertTrue(is_prime(29)) def snake_case__ ( self): '''simple docstring''' with self.assertRaises(__a): is_prime(-19) self.assertFalse( is_prime(0), "Zero doesn't have any positive factors, primes must have exactly two.", ) self.assertFalse( is_prime(1), "One only has 1 positive factor, primes must have exactly two.", ) self.assertFalse(is_prime(2 * 2)) self.assertFalse(is_prime(2 * 3)) self.assertFalse(is_prime(3 * 3)) self.assertFalse(is_prime(3 * 5)) self.assertFalse(is_prime(3 * 5 * 7)) if __name__ == "__main__": unittest.main()
36
"""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 _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__( self , __a , __a=None , __a=True , __a=None , **__a ): __lowerCAmelCase = parent __lowerCAmelCase = config_class __lowerCAmelCase = has_text_modality __lowerCAmelCase = kwargs __lowerCAmelCase = common_properties def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = ( ["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(__a , __a ) , msg=f"`{prop}` does not exist" ) # Test that config has the common properties as setter for idx, name in enumerate(__a ): try: setattr(__a , __a , __a ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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(__a ): try: __lowerCAmelCase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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 ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , __a ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , "config.json" ) config_first.to_json_file(__a ) __lowerCAmelCase = self.config_class.from_json_file(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = "test" with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , __a ) config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a , subfolder=__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) __lowerCAmelCase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def snake_case ( self ): if self.config_class.is_composition: return __lowerCAmelCase = self.config_class() self.parent.assertIsNotNone(__a ) def snake_case ( self ): __lowerCAmelCase = copy.deepcopy(__a ) __lowerCAmelCase = self.config_class(**__a ) __lowerCAmelCase = [] 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(__a , __a ) != value: wrong_values.append((key, getattr(__a , __a ), value) ) if len(__a ) > 0: __lowerCAmelCase = "\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 ): 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()
57
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/config.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/config.json''' # See all FNet models at https://huggingface.co/models?filter=fnet } class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : Optional[Any] = '''fnet''' def __init__( self ,__UpperCAmelCase=3_2000 ,__UpperCAmelCase=768 ,__UpperCAmelCase=12 ,__UpperCAmelCase=3072 ,__UpperCAmelCase="gelu_new" ,__UpperCAmelCase=0.1 ,__UpperCAmelCase=512 ,__UpperCAmelCase=4 ,__UpperCAmelCase=0.0_2 ,__UpperCAmelCase=1E-12 ,__UpperCAmelCase=False ,__UpperCAmelCase=512 ,__UpperCAmelCase=3 ,__UpperCAmelCase=1 ,__UpperCAmelCase=2 ,**__UpperCAmelCase ,) -> str: super().__init__(pad_token_id=__UpperCAmelCase ,bos_token_id=__UpperCAmelCase ,eos_token_id=__UpperCAmelCase ,**__UpperCAmelCase ) lowerCAmelCase__ : Optional[Any] = vocab_size lowerCAmelCase__ : Union[str, Any] = max_position_embeddings lowerCAmelCase__ : Tuple = hidden_size lowerCAmelCase__ : List[Any] = num_hidden_layers lowerCAmelCase__ : Dict = intermediate_size lowerCAmelCase__ : str = hidden_act lowerCAmelCase__ : str = hidden_dropout_prob lowerCAmelCase__ : List[str] = initializer_range lowerCAmelCase__ : str = type_vocab_size lowerCAmelCase__ : Optional[int] = layer_norm_eps lowerCAmelCase__ : int = use_tpu_fourier_optimizations lowerCAmelCase__ : int = tpu_short_seq_length
37
"""simple docstring""" A : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
57
0
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : list[int] ) -> list[int]: """simple docstring""" UpperCamelCase :List[str] = len(__magic_name__ ) for i in range(__magic_name__ ): for j in range(i + 1 , __magic_name__ ): if numbers[j] < numbers[i]: UpperCamelCase , UpperCamelCase :Tuple = numbers[j], numbers[i] return numbers if __name__ == "__main__": UpperCAmelCase_ : Any = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase_ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(exchange_sort(unsorted))
38
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : str = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : str =["""input_ids""", """attention_mask"""] def __init__( self , __a="</s>" , __a="<unk>" , __a="<pad>" , __a=1_25 , __a=None , **__a , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __lowerCAmelCase = [f"<extra_id_{i}>" for i in range(__a )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __lowerCAmelCase = len(set(filter(lambda __a : bool("extra_id" in str(__a ) ) , __a ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the" " extra_ids tokens" ) __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else pad_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else eos_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else unk_token super().__init__( eos_token=__a , unk_token=__a , pad_token=__a , extra_ids=__a , additional_special_tokens=__a , **__a , ) __lowerCAmelCase = extra_ids __lowerCAmelCase = 2**8 # utf is 8 bits # define special tokens dict __lowerCAmelCase = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __lowerCAmelCase = len(self.special_tokens_encoder ) __lowerCAmelCase = len(__a ) for i, token in enumerate(__a ): __lowerCAmelCase = self.vocab_size + i - n __lowerCAmelCase = {v: k for k, v in self.special_tokens_encoder.items()} @property def snake_case ( self ): return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def snake_case ( self , __a , __a = None , __a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__a )) + [1] return ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] def snake_case ( self , __a ): if len(__a ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated" " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = self._add_eos_if_not_present(__a ) if token_ids_a is None: return token_ids_a else: __lowerCAmelCase = self._add_eos_if_not_present(__a ) return token_ids_a + token_ids_a def snake_case ( self , __a ): __lowerCAmelCase = [chr(__a ) for i in text.encode("utf-8" )] return tokens def snake_case ( self , __a ): if token in self.special_tokens_encoder: __lowerCAmelCase = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __lowerCAmelCase = self.added_tokens_encoder[token] elif len(__a ) != 1: __lowerCAmelCase = self.unk_token_id else: __lowerCAmelCase = ord(__a ) + self._num_special_tokens return token_id def snake_case ( self , __a ): if index in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[index] else: __lowerCAmelCase = chr(index - self._num_special_tokens ) return token def snake_case ( self , __a ): __lowerCAmelCase = B"" for token in tokens: if token in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.added_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.special_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) elif token in self.added_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) else: __lowerCAmelCase = bytes([ord(__a )] ) bstring += tok_string __lowerCAmelCase = bstring.decode("utf-8" , errors="ignore" ) return string def snake_case ( self , __a , __a = None ): return ()
57
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def __A ( __lowerCAmelCase )-> Union[str, Any]: """simple docstring""" _UpperCAmelCase = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class __lowerCamelCase ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): """simple docstring""" UpperCamelCase__ = StableDiffusionLatentUpscalePipeline UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { "height", "width", "cross_attention_kwargs", "negative_prompt_embeds", "prompt_embeds", } UpperCamelCase__ = PipelineTesterMixin.required_optional_params - {"num_images_per_prompt"} UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase__ = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCamelCase__ = frozenset([]) UpperCamelCase__ = True @property def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 1 _UpperCAmelCase = 4 _UpperCAmelCase = (16, 16) _UpperCAmelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(UpperCAmelCase ) return image def UpperCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _UpperCAmelCase = UNetaDConditionModel( act_fn='gelu' , attention_head_dim=8 , norm_num_groups=UpperCAmelCase , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=160 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=( 'KDownBlock2D', 'KCrossAttnDownBlock2D', 'KCrossAttnDownBlock2D', 'KCrossAttnDownBlock2D', ) , in_channels=8 , mid_block_type=UpperCAmelCase , only_cross_attention=UpperCAmelCase , out_channels=5 , resnet_time_scale_shift='scale_shift' , time_embedding_type='fourier' , timestep_post_act='gelu' , up_block_types=('KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KUpBlock2D') , ) _UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[ 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', ] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) _UpperCAmelCase = EulerDiscreteScheduler(prediction_type='sample' ) _UpperCAmelCase = 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=1000 , hidden_act='quick_gelu' , projection_dim=512 , ) _UpperCAmelCase = CLIPTextModel(UpperCAmelCase ) _UpperCAmelCase = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _UpperCAmelCase = { 'unet': model.eval(), 'vae': vae.eval(), 'scheduler': scheduler, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase=0 ): """simple docstring""" if str(UpperCAmelCase ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(UpperCAmelCase ) else: _UpperCAmelCase = torch.Generator(device=UpperCAmelCase ).manual_seed(UpperCAmelCase ) _UpperCAmelCase = { 'prompt': 'A painting of a squirrel eating a burger', 'image': self.dummy_image.cpu(), 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 'cpu' _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = self.pipeline_class(**UpperCAmelCase ) pipe.to(UpperCAmelCase ) pipe.set_progress_bar_config(disable=UpperCAmelCase ) _UpperCAmelCase = self.get_dummy_inputs(UpperCAmelCase ) _UpperCAmelCase = pipe(**UpperCAmelCase ).images _UpperCAmelCase = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 256, 256, 3) ) _UpperCAmelCase = np.array( [0.47_22_24_12, 0.41_92_16_33, 0.44_71_74_34, 0.46_87_41_92, 0.42_58_82_58, 0.46_15_07_26, 0.4_67_75_34, 0.45_58_38_32, 0.48_57_90_55] ) _UpperCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(UpperCAmelCase , 1e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=7e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_save_load_local(expected_max_difference=3e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_save_load_optional_components(expected_max_difference=3e-3 ) def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = [ 'DDIMScheduler', 'DDPMScheduler', 'PNDMScheduler', 'HeunDiscreteScheduler', 'EulerAncestralDiscreteScheduler', 'KDPM2DiscreteScheduler', 'KDPM2AncestralDiscreteScheduler', 'DPMSolverSDEScheduler', ] _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = self.pipeline_class(**UpperCAmelCase ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=UpperCAmelCase ) pipe.to(UpperCAmelCase ) pipe.set_progress_bar_config(disable=UpperCAmelCase ) _UpperCAmelCase = self.get_dummy_inputs(UpperCAmelCase ) _UpperCAmelCase = 2 _UpperCAmelCase = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue _UpperCAmelCase = getattr(UpperCAmelCase , scheduler_enum.name ) _UpperCAmelCase = scheduler_cls.from_config(pipe.scheduler.config ) _UpperCAmelCase = pipe(**UpperCAmelCase )[0] outputs.append(UpperCAmelCase ) assert check_same_shape(UpperCAmelCase ) @require_torch_gpu @slow class __lowerCamelCase ( unittest.TestCase): """simple docstring""" def UpperCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = torch.manual_seed(33 ) _UpperCAmelCase = StableDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' , torch_dtype=torch.floataa ) pipe.to('cuda' ) _UpperCAmelCase = StableDiffusionLatentUpscalePipeline.from_pretrained( 'stabilityai/sd-x2-latent-upscaler' , torch_dtype=torch.floataa ) upscaler.to('cuda' ) _UpperCAmelCase = 'a photo of an astronaut high resolution, unreal engine, ultra realistic' _UpperCAmelCase = pipe(UpperCAmelCase , generator=UpperCAmelCase , output_type='latent' ).images _UpperCAmelCase = upscaler( prompt=UpperCAmelCase , image=UpperCAmelCase , num_inference_steps=20 , guidance_scale=0 , generator=UpperCAmelCase , output_type='np' , ).images[0] _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy' ) assert np.abs((expected_image - image).mean() ) < 5e-2 def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = torch.manual_seed(33 ) _UpperCAmelCase = StableDiffusionLatentUpscalePipeline.from_pretrained( 'stabilityai/sd-x2-latent-upscaler' , torch_dtype=torch.floataa ) upscaler.to('cuda' ) _UpperCAmelCase = 'the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas' _UpperCAmelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png' ) _UpperCAmelCase = upscaler( prompt=UpperCAmelCase , image=UpperCAmelCase , num_inference_steps=20 , guidance_scale=0 , generator=UpperCAmelCase , output_type='np' , ).images[0] _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy' ) assert np.abs((expected_image - image).max() ) < 5e-2
39
"""simple docstring""" import numpy # List of input, output pairs A : Any = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) A : str = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) A : Union[str, Any] = [2, 4, 1, 5] A : int = len(train_data) A : Dict = 0.009 def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase="train" ): '''simple docstring''' return calculate_hypothesis_value(_UpperCamelCase , _UpperCamelCase ) - output( _UpperCamelCase , _UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(len(_UpperCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=m ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(_UpperCamelCase ): if index == -1: summation_value += _error(_UpperCamelCase ) else: summation_value += _error(_UpperCamelCase ) * train_data[i][0][index] return summation_value def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = summation_of_cost_derivative(_UpperCamelCase , _UpperCamelCase ) / m return cost_derivative_value def _lowerCamelCase ( ): '''simple docstring''' global parameter_vector # Tune these values to set a tolerance value for predicted output __lowerCAmelCase = 0.00_00_02 __lowerCAmelCase = 0 __lowerCAmelCase = 0 while True: j += 1 __lowerCAmelCase = [0, 0, 0, 0] for i in range(0 , len(_UpperCamelCase ) ): __lowerCAmelCase = get_cost_derivative(i - 1 ) __lowerCAmelCase = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( _UpperCamelCase , _UpperCamelCase , atol=_UpperCamelCase , rtol=_UpperCamelCase , ): break __lowerCAmelCase = temp_parameter_vector print(("Number of iterations:", j) ) def _lowerCamelCase ( ): '''simple docstring''' for i in range(len(_UpperCamelCase ) ): print(("Actual output value:", output(_UpperCamelCase , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(_UpperCamelCase , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
57
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase = { """configuration_ctrl""": ["""CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CTRLConfig"""], """tokenization_ctrl""": ["""CTRLTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ """CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""", """CTRLForSequenceClassification""", """CTRLLMHeadModel""", """CTRLModel""", """CTRLPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ """TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFCTRLForSequenceClassification""", """TFCTRLLMHeadModel""", """TFCTRLModel""", """TFCTRLPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
40
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): __lowerCAmelCase = tempfile.mkdtemp() __lowerCAmelCase = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "的", "价", "格", "是", "15", "便", "alex", "##andra", ",", "。", "-", "t", "shirt", ] __lowerCAmelCase = 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] ) ) __lowerCAmelCase = { "do_resize": True, "size": {"height": 2_24, "width": 2_24}, "do_center_crop": True, "crop_size": {"height": 18, "width": 18}, "do_normalize": True, "image_mean": [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], "image_std": [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], "do_convert_rgb": True, } __lowerCAmelCase = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(__a , __a ) def snake_case ( self , **__a ): return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return BertTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self ): shutil.rmtree(self.tmpdirname ) def snake_case ( self ): __lowerCAmelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCAmelCase = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self ): __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__a ) __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __a ) self.assertIsInstance(processor_fast.tokenizer , __a ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __a ) self.assertIsInstance(processor_fast.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase = self.get_tokenizer(cls_token="(CLS)" , sep_token="(SEP)" ) __lowerCAmelCase = self.get_image_processor(do_normalize=__a ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="(CLS)" , sep_token="(SEP)" , do_normalize=__a ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = image_processor(__a , return_tensors="np" ) __lowerCAmelCase = processor(images=__a , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = processor(text=__a ) __lowerCAmelCase = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(__a ): processor() def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase = processor.batch_decode(__a ) __lowerCAmelCase = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
57
0
'''simple docstring''' from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging _A : int =logging.get_logger(__name__) class _lowercase : a = 42 a = None @staticmethod def lowerCamelCase_ ( ): raise NotImplementedError def lowerCamelCase_ ( self: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: int , UpperCamelCase__: str , **UpperCamelCase__: Union[str, Any] ): raise NotImplementedError def lowerCamelCase_ ( self: Any , UpperCamelCase__: Any ): raise NotImplementedError def lowerCamelCase_ ( self: List[Any] ): if not self.is_available(): raise RuntimeError( F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def lowerCamelCase_ ( cls: Optional[int] ): return F'''`pip install {cls.pip_package or cls.name}`''' class _lowercase ( _lowercase ): a = """optuna""" @staticmethod def lowerCamelCase_ ( ): return is_optuna_available() def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: int , UpperCamelCase__: str , **UpperCamelCase__: Dict ): return run_hp_search_optuna(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: Any ): return default_hp_space_optuna(UpperCamelCase__ ) class _lowercase ( _lowercase ): a = """ray""" a = """'ray[tune]'""" @staticmethod def lowerCamelCase_ ( ): return is_ray_available() def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: str , UpperCamelCase__: int , UpperCamelCase__: str , **UpperCamelCase__: Union[str, Any] ): return run_hp_search_ray(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: Any ): return default_hp_space_ray(UpperCamelCase__ ) class _lowercase ( _lowercase ): a = """sigopt""" @staticmethod def lowerCamelCase_ ( ): return is_sigopt_available() def lowerCamelCase_ ( self: Tuple , UpperCamelCase__: List[Any] , UpperCamelCase__: int , UpperCamelCase__: str , **UpperCamelCase__: Dict ): return run_hp_search_sigopt(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase_ ( self: Tuple , UpperCamelCase__: List[str] ): return default_hp_space_sigopt(UpperCamelCase__ ) class _lowercase ( _lowercase ): a = """wandb""" @staticmethod def lowerCamelCase_ ( ): return is_wandb_available() def lowerCamelCase_ ( self: int , UpperCamelCase__: Tuple , UpperCamelCase__: int , UpperCamelCase__: str , **UpperCamelCase__: int ): return run_hp_search_wandb(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: Union[str, Any] ): return default_hp_space_wandb(UpperCamelCase__ ) _A : Dict ={ HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def SCREAMING_SNAKE_CASE_ () -> str: lowerCamelCase__ : List[str] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(UpperCamelCase ) > 0: lowerCamelCase__ : Dict = available_backends[0].name if len(UpperCamelCase ) > 1: logger.info( f'''{len(UpperCamelCase )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( f''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
41
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( _UpperCamelCase = 4 ): '''simple docstring''' __lowerCAmelCase = abs(_UpperCamelCase ) or 4 return [[1 + x + y * row_size for x in range(_UpperCamelCase )] for y in range(_UpperCamelCase )] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(reverse_column(_UpperCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_column(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [list(_UpperCamelCase ) for x in zip(*_UpperCamelCase )] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = matrix[::-1] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [x[::-1] for x in matrix] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for i in matrix: print(*_UpperCamelCase ) if __name__ == "__main__": A : Dict = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_aa(matrix)) A : List[str] = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_aaa(matrix)) A : str = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_aaa(matrix))
57
0
'''simple docstring''' import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets lowercase : List[Any] = datasets.logging.get_logger(__name__) lowercase : List[str] = "\\n@InProceedings{moosavi2019minimum,\n author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},\n title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},\n year = {2019},\n booktitle = {Proceedings of the 57th Annual Meeting of\n the Association for Computational Linguistics (Volume 1: Long Papers)},\n publisher = {Association for Computational Linguistics},\n address = {Florence, Italy},\n}\n\n@inproceedings{10.3115/1072399.1072405,\nauthor = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},\ntitle = {A Model-Theoretic Coreference Scoring Scheme},\nyear = {1995},\nisbn = {1558604022},\npublisher = {Association for Computational Linguistics},\naddress = {USA},\nurl = {https://doi.org/10.3115/1072399.1072405},\ndoi = {10.3115/1072399.1072405},\nbooktitle = {Proceedings of the 6th Conference on Message Understanding},\npages = {45–52},\nnumpages = {8},\nlocation = {Columbia, Maryland},\nseries = {MUC6 ’95}\n}\n\n@INPROCEEDINGS{Bagga98algorithmsfor,\n author = {Amit Bagga and Breck Baldwin},\n title = {Algorithms for Scoring Coreference Chains},\n booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},\n year = {1998},\n pages = {563--566}\n}\n\n@INPROCEEDINGS{Luo05oncoreference,\n author = {Xiaoqiang Luo},\n title = {On coreference resolution performance metrics},\n booktitle = {In Proc. of HLT/EMNLP},\n year = {2005},\n pages = {25--32},\n publisher = {URL}\n}\n\n@inproceedings{moosavi-strube-2016-coreference,\n title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",\n author = \"Moosavi, Nafise Sadat and\n Strube, Michael\",\n booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",\n month = aug,\n year = \"2016\",\n address = \"Berlin, Germany\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/P16-1060\",\n doi = \"10.18653/v1/P16-1060\",\n pages = \"632--642\",\n}\n\n" lowercase : Union[str, Any] = "\\nCoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which\nimplements of the common evaluation metrics including MUC [Vilain et al, 1995],\nB-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],\nLEA [Moosavi and Strube, 2016] and the averaged CoNLL score\n(the average of the F1 values of MUC, B-cubed and CEAFe)\n[Denis and Baldridge, 2009a; Pradhan et al., 2011].\n\nThis wrapper of CoVal currently only work with CoNLL line format:\nThe CoNLL format has one word per line with all the annotation for this word in column separated by spaces:\nColumn Type Description\n1 Document ID This is a variation on the document filename\n2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.\n3 Word number\n4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.\n5 Part-of-Speech\n6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column.\n7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"\n8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.\n9 Word sense This is the word sense of the word in Column 3.\n10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.\n11 Named Entities These columns identifies the spans representing various named entities.\n12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.\nN Coreference Coreference chain information encoded in a parenthesis structure.\nMore informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html\n\nDetails on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md\n\nCoVal code was written by @ns-moosavi.\nSome parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py\nThe test suite is taken from https://github.com/conll/reference-coreference-scorers/\nMention evaluation and the test suite are added by @andreasvc.\nParsing CoNLL files is developed by Leo Born.\n" lowercase : Tuple = "\nCalculates coreference evaluation metrics.\nArgs:\n predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.\n Each prediction is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.\n Each reference is a word with its annotations as a string made of columns joined with spaces.\n Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)\n See the details on the format in the description of the metric.\n keep_singletons: After extracting all mentions of key or system files,\n mentions whose corresponding coreference chain is of size one,\n are considered as singletons. The default evaluation mode will include\n singletons in evaluations if they are included in the key or the system files.\n By setting 'keep_singletons=False', all singletons in the key and system files\n will be excluded from the evaluation.\n NP_only: Most of the recent coreference resolvers only resolve NP mentions and\n leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.\n min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.\n Minimum spans are determined using the MINA algorithm.\n\nReturns:\n 'mentions': mentions\n 'muc': MUC metric [Vilain et al, 1995]\n 'bcub': B-cubed [Bagga and Baldwin, 1998]\n 'ceafe': CEAFe [Luo et al., 2005]\n 'lea': LEA [Moosavi and Strube, 2016]\n 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)\n\nExamples:\n\n >>> coval = datasets.load_metric('coval')\n >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -',\n ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)',\n ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)',\n ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -',\n ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -',\n ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -']\n >>> references = [words]\n >>> predictions = [words]\n >>> results = coval.compute(predictions=predictions, references=references)\n >>> print(results) # doctest:+ELLIPSIS\n {'mentions/recall': 1.0,[...] 'conll_score': 100.0}\n" def SCREAMING_SNAKE_CASE__ ( __A , __A , __A=False , __A=False , __A=True , __A=False , __A="dummy_doc" ) -> str: _snake_case = {doc: key_lines} _snake_case = {doc: sys_lines} _snake_case = {} _snake_case = 0 _snake_case = 0 _snake_case = 0 _snake_case = 0 _snake_case = 0 _snake_case = 0 _snake_case , _snake_case = reader.get_doc_mentions(__A , key_doc_lines[doc] , __A ) key_singletons_num += singletons_num if NP_only or min_span: _snake_case = reader.set_annotated_parse_trees(__A , key_doc_lines[doc] , __A , __A ) _snake_case , _snake_case = reader.get_doc_mentions(__A , sys_doc_lines[doc] , __A ) sys_singletons_num += singletons_num if NP_only or min_span: _snake_case = reader.set_annotated_parse_trees(__A , key_doc_lines[doc] , __A , __A ) if remove_nested: _snake_case , _snake_case = reader.remove_nested_coref_mentions(__A , __A ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters _snake_case , _snake_case = reader.remove_nested_coref_mentions(__A , __A ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters _snake_case = reader.get_mention_assignments(__A , __A ) _snake_case = reader.get_mention_assignments(__A , __A ) _snake_case = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( 'Number of removed nested coreferring mentions in the key ' F'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( 'Number of resulting singleton clusters in the key ' F'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( F'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' 'files, respectively' ) return doc_coref_infos def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A , __A , __A , __A ) -> Any: _snake_case = get_coref_infos(__A , __A , __A , __A , __A , __A ) _snake_case = {} _snake_case = 0 _snake_case = 0 for name, metric in metrics: _snake_case , _snake_case , _snake_case = evaluator.evaluate_documents(__A , __A , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({F'{name}/recall': recall, F'{name}/precision': precision, F'{name}/f1': fa} ) logger.info( name.ljust(10 ) , F'Recall: {recall * 100:.2f}' , F' Precision: {precision * 100:.2f}' , F' F1: {fa * 100:.2f}' , ) if conll_subparts_num == 3: _snake_case = (conll / 3) * 100 logger.info(F'CoNLL score: {conll:.2f}' ) output_scores.update({'conll_score': conll} ) return output_scores def SCREAMING_SNAKE_CASE__ ( __A ) -> List[Any]: _snake_case = False for line in key_lines: if not line.startswith('#' ): if len(line.split() ) > 6: _snake_case = line.split()[5] if not parse_col == "-": _snake_case = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCAmelCase ( datasets.Metric ): def lowerCamelCase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' ) ), 'references': datasets.Sequence(datasets.Value('string' ) ), } ) , codebase_urls=['https://github.com/ns-moosavi/coval'] , reference_urls=[ 'https://github.com/ns-moosavi/coval', 'https://www.aclweb.org/anthology/P16-1060', 'http://www.conll.cemantix.org/2012/data.html', ] , ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False ): """simple docstring""" _snake_case = [ ('mentions', evaluator.mentions), ('muc', evaluator.muc), ('bcub', evaluator.b_cubed), ('ceafe', evaluator.ceafe), ('lea', evaluator.lea), ] if min_span: _snake_case = util.check_gold_parse_annotation(lowerCAmelCase_ ) if not has_gold_parse: raise NotImplementedError('References should have gold parse annotation to use \'min_span\'.' ) # util.parse_key_file(key_file) # key_file = key_file + ".parsed" _snake_case = evaluate( key_lines=lowerCAmelCase_ , sys_lines=lowerCAmelCase_ , metrics=lowerCAmelCase_ , NP_only=lowerCAmelCase_ , remove_nested=lowerCAmelCase_ , keep_singletons=lowerCAmelCase_ , min_span=lowerCAmelCase_ , ) return score
42
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCAmelCase : Union[str, Any] =TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = TextaTextGenerationPipeline(model=__a , tokenizer=__a ) return generator, ["Something to write", "Something else"] def snake_case ( self , __a , __a ): __lowerCAmelCase = generator("Something there" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["generated_text"].startswith("Something there" ) ) __lowerCAmelCase = generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) __lowerCAmelCase = generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) with self.assertRaises(__a ): generator(4 ) @require_torch def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="pt" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] ) __lowerCAmelCase = 3 __lowerCAmelCase = generator( "Something there" , num_return_sequences=__a , num_beams=__a , ) __lowerCAmelCase = [ {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": ""}, ] self.assertEqual(__a , __a ) __lowerCAmelCase = generator("This is a test" , do_sample=__a , num_return_sequences=2 , return_tensors=__a ) self.assertEqual( __a , [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ] , ) __lowerCAmelCase = generator.model.config.eos_token_id __lowerCAmelCase = "<pad>" __lowerCAmelCase = generator( ["This is a test", "This is a second test"] , do_sample=__a , num_return_sequences=2 , batch_size=2 , return_tensors=__a , ) self.assertEqual( __a , [ [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], ] , ) @require_tf def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="tf" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] )
57
0
def lowerCamelCase ( SCREAMING_SNAKE_CASE = 1_000_000 ): '''simple docstring''' __UpperCamelCase :str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_SNAKE_CASE ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
43
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class _UpperCamelCase ( pl.LightningModule ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCAmelCase = model __lowerCAmelCase = 2 __lowerCAmelCase = nn.Linear(self.model.config.hidden_size , self.num_labels ) def snake_case ( self ): pass def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = LongformerModel.from_pretrained(_UpperCamelCase ) __lowerCAmelCase = LightningModel(_UpperCamelCase ) __lowerCAmelCase = torch.load(_UpperCamelCase , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model __lowerCAmelCase = LongformerForQuestionAnswering.from_pretrained(_UpperCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(_UpperCamelCase ) print(f"Conversion successful. Model saved under {pytorch_dump_folder_path}" ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--longformer_model", default=None, type=str, required=True, help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.", ) parser.add_argument( "--longformer_question_answering_ckpt_path", default=None, type=str, required=True, help="Path the official PyTorch Lightning Checkpoint.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) A : Optional[int] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
57
0
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple ) -> Any: _lowerCAmelCase : Optional[int] = len(_lowerCamelCase ) while cur > 1: # Find the maximum number in arr _lowerCAmelCase : Any = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi _lowerCAmelCase : Union[str, Any] = arr[mi::-1] + arr[mi + 1 : len(_lowerCamelCase )] # Reverse whole list _lowerCAmelCase : Dict = arr[cur - 1 :: -1] + arr[cur : len(_lowerCamelCase )] cur -= 1 return arr if __name__ == "__main__": _a : Union[str, Any] = input('Enter numbers separated by a comma:\n').strip() _a : Dict = [int(item) for item in user_input.split(',')] print(pancake_sort(unsorted))
44
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = False while is_sorted is False: # Until all the indices are traversed keep looping __lowerCAmelCase = True for i in range(0 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False for i in range(1 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False return input_list if __name__ == "__main__": print("Enter list to be sorted") A : Union[str, Any] = [int(x) for x in input().split()] # inputing elements of the list in one line A : str = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
57
0
"""simple docstring""" from __future__ import annotations def lowercase ( lowerCAmelCase__ : list[list[int]] ) -> int: # preprocessing the first row for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(lowerCAmelCase__ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(lowerCAmelCase__ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
45
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =["""image_processor""", """tokenizer"""] __UpperCAmelCase : Optional[Any] ="""CLIPImageProcessor""" __UpperCAmelCase : Union[str, Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): __lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) __lowerCAmelCase = kwargs.pop("feature_extractor" ) __lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self , __a=None , __a=None , __a=None , **__a ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __lowerCAmelCase = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: __lowerCAmelCase = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: __lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): __lowerCAmelCase = self.tokenizer.model_input_names __lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
57
0
"""simple docstring""" import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' lowerCAmelCase = tmp_path / """cache""" lowerCAmelCase = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCAmelCase = TextDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , keep_in_memory=SCREAMING_SNAKE_CASE ).read() _check_text_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ] , ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' lowerCAmelCase = tmp_path / """cache""" lowerCAmelCase = {"""text""": """string"""} lowerCAmelCase = features.copy() if features else default_expected_features lowerCAmelCase = ( Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCAmelCase = TextDatasetReader(SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_text_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str ): '''simple docstring''' lowerCAmelCase = tmp_path / """cache""" lowerCAmelCase = {"""text""": """string"""} lowerCAmelCase = TextDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , split=SCREAMING_SNAKE_CASE ).read() _check_text_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Union[str, Any] ): '''simple docstring''' if issubclass(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowerCAmelCase = text_path elif issubclass(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowerCAmelCase = [text_path] lowerCAmelCase = tmp_path / """cache""" lowerCAmelCase = {"""text""": """string"""} lowerCAmelCase = TextDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_text_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : Tuple=("train",) ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for split in splits: lowerCAmelCase = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple ): '''simple docstring''' lowerCAmelCase = tmp_path / """cache""" lowerCAmelCase = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCAmelCase = TextDatasetReader({"""train""": text_path} , cache_dir=SCREAMING_SNAKE_CASE , keep_in_memory=SCREAMING_SNAKE_CASE ).read() _check_text_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ] , ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : str ): '''simple docstring''' lowerCAmelCase = tmp_path / """cache""" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" lowerCAmelCase = {"""text""": """string"""} lowerCAmelCase = features.copy() if features else default_expected_features lowerCAmelCase = ( Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCAmelCase = TextDatasetReader({"""train""": text_path} , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_text_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' if split: lowerCAmelCase = {split: text_path} else: lowerCAmelCase = """train""" lowerCAmelCase = {"""train""": text_path, """test""": text_path} lowerCAmelCase = tmp_path / """cache""" lowerCAmelCase = {"""text""": """string"""} lowerCAmelCase = TextDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_text_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
46
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class _UpperCamelCase : '''simple docstring''' pass
57
0
'''simple docstring''' from statistics import mean import numpy as np def _lowerCAmelCase ( _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : int ) -> list: """simple docstring""" _SCREAMING_SNAKE_CASE =0 # Number of processes finished _SCREAMING_SNAKE_CASE =0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. _SCREAMING_SNAKE_CASE =[0] * no_of_process # List to include calculation results _SCREAMING_SNAKE_CASE =[0] * no_of_process # Sort by arrival time. _SCREAMING_SNAKE_CASE =[burst_time[i] for i in np.argsort(_UpperCamelCase )] _SCREAMING_SNAKE_CASE =[process_name[i] for i in np.argsort(_UpperCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: _SCREAMING_SNAKE_CASE =0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: _SCREAMING_SNAKE_CASE =arrival_time[i] _SCREAMING_SNAKE_CASE =0 # Index showing the location of the process being performed _SCREAMING_SNAKE_CASE =0 # Saves the current response ratio. _SCREAMING_SNAKE_CASE =0 for i in range(0 , _UpperCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: _SCREAMING_SNAKE_CASE =(burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: _SCREAMING_SNAKE_CASE =temp _SCREAMING_SNAKE_CASE =i # Calculate the turn around time _SCREAMING_SNAKE_CASE =current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. _SCREAMING_SNAKE_CASE =1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def _lowerCAmelCase ( _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : int ) -> list: """simple docstring""" _SCREAMING_SNAKE_CASE =[0] * no_of_process for i in range(0 , _UpperCamelCase ): _SCREAMING_SNAKE_CASE =turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": lowerCamelCase : Dict = 5 lowerCamelCase : Optional[int] = ["A", "B", "C", "D", "E"] lowerCamelCase : Tuple = [1, 2, 3, 4, 5] lowerCamelCase : str = [1, 2, 3, 4, 5] lowerCamelCase : Tuple = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) lowerCamelCase : Optional[Any] = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(0, no_of_process): print( f'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t''' f'''{turn_around_time[i]}\t\t\t{waiting_time[i]}''' ) print(f'''average waiting time : {mean(waiting_time):.5f}''') print(f'''average turn around time : {mean(turn_around_time):.5f}''')
47
"""simple docstring""" import sys from collections import defaultdict class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): return self.node_position[vertex] def snake_case ( self , __a , __a ): __lowerCAmelCase = pos def snake_case ( self , __a , __a , __a , __a ): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCAmelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCAmelCase = 2 * start + 1 else: __lowerCAmelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCAmelCase , __lowerCAmelCase = heap[smallest_child], positions[smallest_child] __lowerCAmelCase , __lowerCAmelCase = ( heap[start], positions[start], ) __lowerCAmelCase , __lowerCAmelCase = temp, tempa __lowerCAmelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __a ) self.top_to_bottom(__a , __a , __a , __a ) def snake_case ( self , __a , __a , __a , __a ): __lowerCAmelCase = position[index] while index != 0: __lowerCAmelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCAmelCase = heap[parent] __lowerCAmelCase = position[parent] self.set_position(position[parent] , __a ) else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , __a ) break __lowerCAmelCase = parent else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , 0 ) def snake_case ( self , __a , __a ): __lowerCAmelCase = len(__a ) // 2 - 1 for i in range(__a , -1 , -1 ): self.top_to_bottom(__a , __a , len(__a ) , __a ) def snake_case ( self , __a , __a ): __lowerCAmelCase = positions[0] __lowerCAmelCase = sys.maxsize self.top_to_bottom(__a , 0 , len(__a ) , __a ) return temp def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = Heap() __lowerCAmelCase = [0] * len(_UpperCamelCase ) __lowerCAmelCase = [-1] * len(_UpperCamelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCAmelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCAmelCase = [] for vertex in range(len(_UpperCamelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_UpperCamelCase ) heap.node_position.append(_UpperCamelCase ) __lowerCAmelCase = [] __lowerCAmelCase = 1 __lowerCAmelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCAmelCase = 0 __lowerCAmelCase = distance heap.heapify(_UpperCamelCase , _UpperCamelCase ) for _ in range(1 , len(_UpperCamelCase ) ): __lowerCAmelCase = heap.delete_minimum(_UpperCamelCase , _UpperCamelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCAmelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_UpperCamelCase )] ): __lowerCAmelCase = distance heap.bottom_to_top( _UpperCamelCase , heap.get_position(_UpperCamelCase ) , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A : Optional[Any] = int(input("Enter number of edges: ").strip()) A : Dict = defaultdict(list) for _ in range(edges_number): A : str = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
57
0
from __future__ import annotations import math def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> int: if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 ,node_index * 2 ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ,minimax(depth + 1 ,node_index * 2 + 1 ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ,) if is_max else min( minimax(depth + 1 ,node_index * 2 ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ,minimax(depth + 1 ,node_index * 2 + 1 ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ,) ) def A ( ) -> None: lowerCamelCase : Any = [90, 23, 6, 33, 21, 65, 123, 3_4423] lowerCamelCase : Tuple = math.log(len(_SCREAMING_SNAKE_CASE ) ,2 ) print(f'''Optimal value : {minimax(0 ,0 ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
48
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() A : Tuple = logging.get_logger(__name__) A : Tuple = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] A : Optional[Any] = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = torch.load(_UpperCamelCase , map_location="cpu" ) return sd def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=rename_keys_prefix ): '''simple docstring''' __lowerCAmelCase = OrderedDict() __lowerCAmelCase = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __lowerCAmelCase = key for name_pair in rename_keys_prefix: __lowerCAmelCase = new_key.replace(name_pair[0] , name_pair[1] ) __lowerCAmelCase = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __lowerCAmelCase = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}." # Get Config if "pre" in checkpoint_path: __lowerCAmelCase = "pretraining" if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 1024} else: raise NotImplementedError(f"No implementation found for `{checkpoint_path}`." ) else: if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} __lowerCAmelCase = "multichoice" elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} __lowerCAmelCase = "vqa_advanced" elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048, "num_labels": 3129} __lowerCAmelCase = "vqa" elif "nlvr" in checkpoint_path: __lowerCAmelCase = { "visual_embedding_dim": 1024, "num_labels": 2, } __lowerCAmelCase = "nlvr" __lowerCAmelCase = VisualBertConfig(**_UpperCamelCase ) # Load State Dict __lowerCAmelCase = load_state_dict(_UpperCamelCase ) __lowerCAmelCase = get_new_dict(_UpperCamelCase , _UpperCamelCase ) if model_type == "pretraining": __lowerCAmelCase = VisualBertForPreTraining(_UpperCamelCase ) elif model_type == "vqa": __lowerCAmelCase = VisualBertForQuestionAnswering(_UpperCamelCase ) elif model_type == "nlvr": __lowerCAmelCase = VisualBertForVisualReasoning(_UpperCamelCase ) elif model_type == "multichoice": __lowerCAmelCase = VisualBertForMultipleChoice(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Save Checkpoints Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") A : Optional[int] = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
57
0
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 __snake_case :Dict = '''▁''' __snake_case :Tuple = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A ( __UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ : Dict = BertGenerationTokenizer UpperCamelCase__ : Optional[Any] = False UpperCamelCase__ : List[str] = True def _lowerCamelCase ( self : Dict): '''simple docstring''' super().setUp() __a = BertGenerationTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE) tokenizer.save_pretrained(self.tmpdirname) def _lowerCamelCase ( self : int): '''simple docstring''' __a = '''<s>''' __a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE) , __SCREAMING_SNAKE_CASE) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE) , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Tuple): '''simple docstring''' __a = 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(__SCREAMING_SNAKE_CASE) , 1_002) def _lowerCamelCase ( self : Optional[Any]): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_000) def _lowerCamelCase ( self : str): '''simple docstring''' __a = BertGenerationTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE) __a = tokenizer.tokenize('''This is a test''') self.assertListEqual(__SCREAMING_SNAKE_CASE , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE) , [285, 46, 10, 170, 382] , ) __a = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( __SCREAMING_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''', '''é''', '''.''', ] , ) __a = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE) self.assertListEqual( __SCREAMING_SNAKE_CASE , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __a = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE) self.assertListEqual( __SCREAMING_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 _lowerCamelCase ( self : Optional[int]): '''simple docstring''' return BertGenerationTokenizer.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder''') @slow def _lowerCamelCase ( self : Dict): '''simple docstring''' __a = '''Hello World!''' __a = [18_536, 2_260, 101] self.assertListEqual(__SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(__SCREAMING_SNAKE_CASE)) @slow def _lowerCamelCase ( self : Optional[Any]): '''simple docstring''' __a = ( '''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''' ) __a = [ 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, ] self.assertListEqual(__SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(__SCREAMING_SNAKE_CASE)) @require_torch @slow def _lowerCamelCase ( self : Dict): '''simple docstring''' import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __a = list(self.big_tokenizer.get_vocab().keys())[:10] __a = ''' '''.join(__SCREAMING_SNAKE_CASE) __a = self.big_tokenizer.encode_plus(__SCREAMING_SNAKE_CASE , return_tensors='''pt''' , return_token_type_ids=__SCREAMING_SNAKE_CASE) __a = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=__SCREAMING_SNAKE_CASE) __a = BertGenerationConfig() __a = BertGenerationEncoder(__SCREAMING_SNAKE_CASE) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__SCREAMING_SNAKE_CASE) model(**__SCREAMING_SNAKE_CASE) @slow def _lowerCamelCase ( self : Any): '''simple docstring''' __a = {'''input_ids''': [[39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114], [448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__SCREAMING_SNAKE_CASE , model_name='''google/bert_for_seq_generation_L-24_bbc_encoder''' , revision='''c817d1fd1be2ffa69431227a1fe320544943d4db''' , )
49
"""simple docstring""" class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [ [], [], [], ] def snake_case ( self , __a , __a ): try: if len(self.queues[priority] ) >= 1_00: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(__a ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def snake_case ( self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues ) ) class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): if len(self.queue ) == 1_00: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(__a ) def snake_case ( self ): if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(__a ) return data def __str__( self ): return str(self.queue ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
57
0
from math import factorial def SCREAMING_SNAKE_CASE ( _UpperCAmelCase = 100 ) -> int: return sum(map(_UpperCAmelCase , str(factorial(_UpperCAmelCase ) ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
50
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' 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\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) __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()
57
0
# 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 re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __snake_case ( a ): UpperCAmelCase__ : Union[str, Any] = '''naver-clova-ix/donut-base-finetuned-docvqa''' UpperCAmelCase__ : List[Any] = ( '''This is a tool that answers a question about an document (pdf). It takes an input named `document` which ''' '''should be the document containing the information, as well as a `question` that is the question about the ''' '''document. It returns a text that contains the answer to the question.''' ) UpperCAmelCase__ : str = '''document_qa''' UpperCAmelCase__ : Dict = AutoProcessor UpperCAmelCase__ : List[str] = VisionEncoderDecoderModel UpperCAmelCase__ : str = ['''image''', '''text'''] UpperCAmelCase__ : Union[str, Any] = ['''text'''] def __init__( self : List[Any] , *_snake_case : Union[str, Any] , **_snake_case : List[str]): """simple docstring""" if not is_vision_available(): raise ValueError('''Pillow must be installed to use the DocumentQuestionAnsweringTool.''') super().__init__(*_snake_case , **_snake_case) def lowerCamelCase ( self : Optional[Any] , _snake_case : "Image" , _snake_case : str): """simple docstring""" UpperCAmelCase_ = '''<s_docvqa><s_question>{user_input}</s_question><s_answer>''' UpperCAmelCase_ = task_prompt.replace('''{user_input}''' , _snake_case) UpperCAmelCase_ = self.pre_processor.tokenizer( _snake_case , add_special_tokens=_snake_case , return_tensors='''pt''').input_ids UpperCAmelCase_ = self.pre_processor(_snake_case , return_tensors='''pt''').pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def lowerCamelCase ( self : Optional[int] , _snake_case : List[str]): """simple docstring""" return self.model.generate( inputs['''pixel_values'''].to(self.device) , decoder_input_ids=inputs['''decoder_input_ids'''].to(self.device) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=_snake_case , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=_snake_case , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=_snake_case , ).sequences def lowerCamelCase ( self : Optional[Any] , _snake_case : Any): """simple docstring""" UpperCAmelCase_ = self.pre_processor.batch_decode(_snake_case)[0] UpperCAmelCase_ = sequence.replace(self.pre_processor.tokenizer.eos_token , '''''') UpperCAmelCase_ = sequence.replace(self.pre_processor.tokenizer.pad_token , '''''') UpperCAmelCase_ = re.sub(r'''<.*?>''' , '''''' , _snake_case , count=1).strip() # remove first task start token UpperCAmelCase_ = self.pre_processor.tokenajson(_snake_case) return sequence["answer"]
51
"""simple docstring""" def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = 1 while len(_UpperCamelCase ) < 1e6: constant.append(str(_UpperCamelCase ) ) i += 1 __lowerCAmelCase = "".join(_UpperCamelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
57
0
import sys from collections import defaultdict class A__ : def __init__( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] def __UpperCamelCase( self , A_ ): '''simple docstring''' return self.node_position[vertex] def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = pos def __UpperCamelCase( self , A_ , A_ , A_ , A_ ): '''simple docstring''' if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCamelCase : List[Any] = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCamelCase : Any = 2 * start + 1 else: UpperCamelCase : str = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCamelCase , UpperCamelCase : str = heap[smallest_child], positions[smallest_child] UpperCamelCase , UpperCamelCase : Union[str, Any] = ( heap[start], positions[start], ) UpperCamelCase , UpperCamelCase : Optional[Any] = temp, tempa UpperCamelCase : Any = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , A_ ) self.top_to_bottom(A_ , A_ , A_ , A_ ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : Any = position[index] while index != 0: UpperCamelCase : Optional[Any] = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCamelCase : Dict = heap[parent] UpperCamelCase : int = position[parent] self.set_position(position[parent] , A_ ) else: UpperCamelCase : Optional[int] = val UpperCamelCase : Tuple = temp self.set_position(A_ , A_ ) break UpperCamelCase : List[Any] = parent else: UpperCamelCase : Dict = val UpperCamelCase : Tuple = temp self.set_position(A_ , 0 ) def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Tuple = len(A_ ) // 2 - 1 for i in range(A_ , -1 , -1 ): self.top_to_bottom(A_ , A_ , len(A_ ) , A_ ) def __UpperCamelCase( self , A_ , A_ ): '''simple docstring''' UpperCamelCase : Optional[Any] = positions[0] UpperCamelCase : Any = sys.maxsize self.top_to_bottom(A_ , 0 , len(A_ ) , A_ ) return temp def A_ ( _lowerCAmelCase ) -> Any: UpperCamelCase : List[Any] = Heap() UpperCamelCase : Union[str, Any] = [0] * len(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = [-1] * len(_lowerCAmelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCamelCase : Tuple = [] # Heap of Distance of vertices from their neighboring vertex UpperCamelCase : Optional[Any] = [] for vertex in range(len(_lowerCAmelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_lowerCAmelCase ) heap.node_position.append(_lowerCAmelCase ) UpperCamelCase : int = [] UpperCamelCase : Any = 1 UpperCamelCase : List[Any] = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCamelCase : List[Any] = 0 UpperCamelCase : int = distance heap.heapify(_lowerCAmelCase , _lowerCAmelCase ) for _ in range(1 , len(_lowerCAmelCase ) ): UpperCamelCase : str = heap.delete_minimum(_lowerCAmelCase , _lowerCAmelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) UpperCamelCase : Tuple = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_lowerCAmelCase )] ): UpperCamelCase : Any = distance heap.bottom_to_top( _lowerCAmelCase , heap.get_position(_lowerCAmelCase ) , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : Union[str, Any] = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > __lowerCamelCase : Any = int(input("""Enter number of edges: """).strip()) __lowerCamelCase : Optional[Any] = defaultdict(list) for _ in range(edges_number): __lowerCamelCase : Optional[int] = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
52
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs A : Union[str, Any] = imread(R"digital_image_processing/image_data/lena_small.jpg") A : Optional[Any] = cvtColor(img, COLOR_BGR2GRAY) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = cn.convert_to_negative(_UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def _lowerCamelCase ( ): '''simple docstring''' with Image.open("digital_image_processing/image_data/lena_small.jpg" ) as img: # Work around assertion for response assert str(cc.change_contrast(_UpperCamelCase , 110 ) ).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = imread("digital_image_processing/image_data/lena_small.jpg" , 0 ) # assert ambiguous array for all == True assert canny_img.all() __lowerCAmelCase = canny.canny(_UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def _lowerCamelCase ( ): '''simple docstring''' assert gg.gaussian_filter(_UpperCamelCase , 5 , sigma=0.9 ).all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __lowerCAmelCase = conv.img_convolve(_UpperCamelCase , _UpperCamelCase ).astype(_UpperCamelCase ) assert res.any() def _lowerCamelCase ( ): '''simple docstring''' assert med.median_filter(_UpperCamelCase , 3 ).any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase = sob.sobel_filter(_UpperCamelCase ) assert grad.any() and theta.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = sp.make_sepia(_UpperCamelCase , 20 ) assert sepia.all() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' __lowerCAmelCase = bs.Burkes(imread(_UpperCamelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' __lowerCAmelCase = rs.NearestNeighbour(imread(_UpperCamelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. __lowerCAmelCase = imread(_UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = image[x_coordinate][y_coordinate] __lowerCAmelCase = lbp.get_neighbors_pixel( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __lowerCAmelCase = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __lowerCAmelCase = lbp.local_binary_value(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert lbp_image.any()
57
0
'''simple docstring''' import string def lowercase__ ( __lowercase : str ) -> str: """simple docstring""" __UpperCamelCase = '' for i in sequence: __UpperCamelCase = ord(__lowercase ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def lowercase__ ( __lowercase : str ) -> str: """simple docstring""" __UpperCamelCase = string.ascii_letters __UpperCamelCase = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(__lowercase )] if c in letters else c for c in sequence ) def lowercase__ ( ) -> None: """simple docstring""" from timeit import timeit print('Running performance benchmarks...' ) __UpperCamelCase = 'from string import printable ; from __main__ import atbash, atbash_slow' print(F'''> atbash_slow(): {timeit('atbash_slow(printable)' , setup=__lowercase )} seconds''' ) print(F'''> atbash(): {timeit('atbash(printable)' , setup=__lowercase )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f'{example} encrypted in atbash: {atbash(example)}') benchmark()
53
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : Optional[int] = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltCLIPTextConfig", "AltCLIPVisionConfig", ], "processing_altclip": ["AltCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = [ "ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "AltCLIPPreTrainedModel", "AltCLIPModel", "AltCLIPTextModel", "AltCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys A : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ = 4 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = abs(lowerCAmelCase_ ) or 4 return [[1 + x + y * row_size for x in range(lowerCAmelCase_ )] for y in range(lowerCAmelCase_ )] def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return reverse_row(transpose(lowerCAmelCase_ ) ) # OR.. transpose(reverse_column(matrix)) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return reverse_row(reverse_column(lowerCAmelCase_ ) ) # OR.. reverse_column(reverse_row(matrix)) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return reverse_column(transpose(lowerCAmelCase_ ) ) # OR.. transpose(reverse_row(matrix)) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [list(lowerCAmelCase_ ) for x in zip(*lowerCAmelCase_ )] return matrix def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = matrix[::-1] return matrix def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [x[::-1] for x in matrix] return matrix def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' for i in matrix: print(*lowerCAmelCase_ ) if __name__ == "__main__": a__ : Optional[Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) a__ : Union[str, Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) a__ : List[Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
54
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A : Dict = logging.getLogger(__name__) @dataclass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[float] =field( default=0.0 ,metadata={"""help""": """The label smoothing epsilon to apply (if not zero)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """Whether to SortishSamler or not."""} ) __UpperCAmelCase : bool =field( default=lowerCAmelCase__ ,metadata={"""help""": """Whether to use generate to calculate generative metrics (ROUGE, BLEU)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """whether to use adafactor"""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Encoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Decoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field(default=lowerCAmelCase__ ,metadata={"""help""": """Dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Attention dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[str] =field( default="""linear""" ,metadata={"""help""": F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} ,)
57
0
'''simple docstring''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def __snake_case ( ): lowerCamelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png" lowerCamelCase_ = Image.open(requests.get(UpperCAmelCase_ , stream=UpperCAmelCase_ ).raw ).convert("RGB" ) return image def __snake_case ( UpperCAmelCase_ : int ): lowerCamelCase_ = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.layernorm.bias") ) # fmt: on return rename_keys def __snake_case ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict ): lowerCamelCase_ = dct.pop(UpperCAmelCase_ ) lowerCamelCase_ = val def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] ): for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases lowerCamelCase_ = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) lowerCamelCase_ = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict lowerCamelCase_ = torch.cat((q_bias, torch.zeros_like(UpperCAmelCase_ , requires_grad=UpperCAmelCase_ ), v_bias) ) lowerCamelCase_ = qkv_bias def __snake_case ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int ): lowerCamelCase_ = 364 if "coco" in model_name else 224 lowerCamelCase_ = BlipaVisionConfig(image_size=UpperCAmelCase_ ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: lowerCamelCase_ = OPTConfig.from_pretrained("facebook/opt-2.7b" , eos_token_id=UpperCAmelCase_ ).to_dict() elif "opt-6.7b" in model_name: lowerCamelCase_ = OPTConfig.from_pretrained("facebook/opt-6.7b" , eos_token_id=UpperCAmelCase_ ).to_dict() elif "t5-xl" in model_name: lowerCamelCase_ = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: lowerCamelCase_ = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() lowerCamelCase_ = BlipaConfig(vision_config=UpperCAmelCase_ , text_config=UpperCAmelCase_ ) return config, image_size @torch.no_grad() def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Union[str, Any]=False ): lowerCamelCase_ = ( AutoTokenizer.from_pretrained("facebook/opt-2.7b" ) if "opt" in model_name else AutoTokenizer.from_pretrained("google/flan-t5-xl" ) ) lowerCamelCase_ = tokenizer("\n" , add_special_tokens=UpperCAmelCase_ ).input_ids[0] lowerCamelCase_ ,lowerCamelCase_ = get_blipa_config(UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) lowerCamelCase_ = BlipaForConditionalGeneration(UpperCAmelCase_ ).eval() lowerCamelCase_ = { "blip2-opt-2.7b": ("blip2_opt", "pretrain_opt2.7b"), "blip2-opt-6.7b": ("blip2_opt", "pretrain_opt6.7b"), "blip2-opt-2.7b-coco": ("blip2_opt", "caption_coco_opt2.7b"), "blip2-opt-6.7b-coco": ("blip2_opt", "caption_coco_opt6.7b"), "blip2-flan-t5-xl": ("blip2_t5", "pretrain_flant5xl"), "blip2-flan-t5-xl-coco": ("blip2_t5", "caption_coco_flant5xl"), "blip2-flan-t5-xxl": ("blip2_t5", "pretrain_flant5xxl"), } lowerCamelCase_ ,lowerCamelCase_ = model_name_to_original[model_name] # load original model print("Loading original model..." ) lowerCamelCase_ = "cuda" if torch.cuda.is_available() else "cpu" lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = load_model_and_preprocess( name=UpperCAmelCase_ , model_type=UpperCAmelCase_ , is_eval=UpperCAmelCase_ , device=UpperCAmelCase_ ) original_model.eval() print("Done!" ) # update state dict keys lowerCamelCase_ = original_model.state_dict() lowerCamelCase_ = create_rename_keys(UpperCAmelCase_ ) for src, dest in rename_keys: rename_key(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): lowerCamelCase_ = state_dict.pop(UpperCAmelCase_ ) if key.startswith("Qformer.bert" ): lowerCamelCase_ = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: lowerCamelCase_ = key.replace("self" , "attention" ) if "opt_proj" in key: lowerCamelCase_ = key.replace("opt_proj" , "language_projection" ) if "t5_proj" in key: lowerCamelCase_ = key.replace("t5_proj" , "language_projection" ) if key.startswith("opt" ): lowerCamelCase_ = key.replace("opt" , "language" ) if key.startswith("t5" ): lowerCamelCase_ = key.replace("t5" , "language" ) lowerCamelCase_ = val # read in qv biases read_in_q_v_bias(UpperCAmelCase_ , UpperCAmelCase_ ) lowerCamelCase_ ,lowerCamelCase_ = hf_model.load_state_dict(UpperCAmelCase_ , strict=UpperCAmelCase_ ) assert len(UpperCAmelCase_ ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] lowerCamelCase_ = load_demo_image() lowerCamelCase_ = vis_processors["eval"](UpperCAmelCase_ ).unsqueeze(0 ).to(UpperCAmelCase_ ) lowerCamelCase_ = tokenizer(["\n"] , return_tensors="pt" ).input_ids.to(UpperCAmelCase_ ) # create processor lowerCamelCase_ = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=UpperCAmelCase_ , image_std=UpperCAmelCase_ ) lowerCamelCase_ = BlipaProcessor(image_processor=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ ) lowerCamelCase_ = processor(images=UpperCAmelCase_ , return_tensors="pt" ).pixel_values.to(UpperCAmelCase_ ) # make sure processor creates exact same pixel values assert torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) original_model.to(UpperCAmelCase_ ) hf_model.to(UpperCAmelCase_ ) with torch.no_grad(): if "opt" in model_name: lowerCamelCase_ = original_model({"image": original_pixel_values, "text_input": [""]} ).logits lowerCamelCase_ = hf_model(UpperCAmelCase_ , UpperCAmelCase_ ).logits else: lowerCamelCase_ = original_model( {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]} ).logits lowerCamelCase_ = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) lowerCamelCase_ = hf_model(UpperCAmelCase_ , UpperCAmelCase_ , labels=UpperCAmelCase_ ).logits assert original_logits.shape == logits.shape print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": lowerCamelCase_ = torch.tensor( [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=UpperCAmelCase_ ) assert torch.allclose(logits[0, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": lowerCamelCase_ = torch.tensor( [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=UpperCAmelCase_ ) else: # cast to same type lowerCamelCase_ = logits.dtype assert torch.allclose(original_logits.to(UpperCAmelCase_ ) , UpperCAmelCase_ , atol=1E-2 ) print("Looks ok!" ) print("Generating a caption..." ) lowerCamelCase_ = "" lowerCamelCase_ = tokenizer(UpperCAmelCase_ , return_tensors="pt" ).input_ids.to(UpperCAmelCase_ ) lowerCamelCase_ = original_model.generate({"image": original_pixel_values} ) lowerCamelCase_ = hf_model.generate( UpperCAmelCase_ , UpperCAmelCase_ , do_sample=UpperCAmelCase_ , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("Original generation:" , UpperCAmelCase_ ) lowerCamelCase_ = input_ids.shape[1] lowerCamelCase_ = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=UpperCAmelCase_ ) lowerCamelCase_ = [text.strip() for text in output_text] print("HF generation:" , UpperCAmelCase_ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(UpperCAmelCase_ ) hf_model.save_pretrained(UpperCAmelCase_ ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": a_ : Union[str, Any] = argparse.ArgumentParser() a_ : Optional[Any] = [ """blip2-opt-2.7b""", """blip2-opt-6.7b""", """blip2-opt-2.7b-coco""", """blip2-opt-6.7b-coco""", """blip2-flan-t5-xl""", """blip2-flan-t5-xl-coco""", """blip2-flan-t5-xxl""", ] parser.add_argument( """--model_name""", default="""blip2-opt-2.7b""", choices=choices, type=str, help="""Path to hf config.json of model to convert""", ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub after converting""", ) a_ : Any = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
55
"""simple docstring""" import argparse import os import re import packaging.version A : Any = "examples/" A : Optional[Any] = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } A : Optional[int] = { "init": "src/transformers/__init__.py", "setup": "setup.py", } A : List[Any] = "README.md" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , _UpperCamelCase ) __lowerCAmelCase = re_pattern.sub(_UpperCamelCase , _UpperCamelCase ) with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for folder, directories, fnames in os.walk(_UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase , pattern="examples" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if not patch: update_version_in_examples(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(_UpperCamelCase ).groups()[0] return packaging.version.parse(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase=False ): '''simple docstring''' __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __lowerCAmelCase = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(f"Which version are you releasing? [{default_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = default_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase , patch=_UpperCamelCase ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = get_version() __lowerCAmelCase = f"{current_version.major}.{current_version.minor + 1}.0.dev0" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(f"Which version are we developing now? [{dev_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = dev_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") A : Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
57
0
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants a : Any = Mapping[str, np.ndarray] a : Tuple = Mapping[str, Any] # Is a nested dict. a : Union[str, Any] = 0.01 @dataclasses.dataclass(frozen=_lowerCamelCase ) class a : snake_case_ = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. snake_case_ = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. snake_case_ = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. snake_case_ = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. snake_case_ = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions snake_case_ = None # Optional remark about the protein. Included as a comment in output PDB # files snake_case_ = None # Templates used to generate this protein (prediction-only) snake_case_ = None # Chain corresponding to each parent snake_case_ = None def __magic_name__ ( __UpperCAmelCase ) -> Protein: '''simple docstring''' snake_case_ = r'''(\[[A-Z]+\]\n)''' snake_case_ = [tag.strip() for tag in re.split(__UpperCAmelCase, __UpperCAmelCase ) if len(__UpperCAmelCase ) > 0] snake_case_ = zip(tags[0::2], [l.split('''\n''' ) for l in tags[1::2]] ) snake_case_ = ["N", "CA", "C"] snake_case_ = None snake_case_ = None snake_case_ = None for g in groups: if "[PRIMARY]" == g[0]: snake_case_ = g[1][0].strip() for i in range(len(__UpperCAmelCase ) ): if seq[i] not in residue_constants.restypes: snake_case_ = '''X''' # FIXME: strings are immutable snake_case_ = np.array( [residue_constants.restype_order.get(__UpperCAmelCase, residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: snake_case_ = [] for axis in range(3 ): tertiary.append(list(map(__UpperCAmelCase, g[1][axis].split() ) ) ) snake_case_ = np.array(__UpperCAmelCase ) snake_case_ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(__UpperCAmelCase ): snake_case_ = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: snake_case_ = np.array(list(map({'''-''': 0, '''+''': 1}.get, g[1][0].strip() ) ) ) snake_case_ = np.zeros( ( len(__UpperCAmelCase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(__UpperCAmelCase ): snake_case_ = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=__UpperCAmelCase, atom_mask=__UpperCAmelCase, aatype=__UpperCAmelCase, residue_index=np.arange(len(__UpperCAmelCase ) ), b_factors=__UpperCAmelCase, ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase = 0 ) -> List[str]: '''simple docstring''' snake_case_ = [] snake_case_ = prot.remark if remark is not None: pdb_headers.append(F"REMARK {remark}" ) snake_case_ = prot.parents snake_case_ = prot.parents_chain_index if parents is not None and parents_chain_index is not None: snake_case_ = [p for i, p in zip(__UpperCAmelCase, __UpperCAmelCase ) if i == chain_id] if parents is None or len(__UpperCAmelCase ) == 0: snake_case_ = ['''N/A'''] pdb_headers.append(F"PARENT {' '.join(__UpperCAmelCase )}" ) return pdb_headers def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> str: '''simple docstring''' snake_case_ = [] snake_case_ = pdb_str.split('''\n''' ) snake_case_ = prot.remark if remark is not None: out_pdb_lines.append(F"REMARK {remark}" ) snake_case_ = 42 if prot.parents is not None and len(prot.parents ) > 0: snake_case_ = [] if prot.parents_chain_index is not None: snake_case_ = {} for p, i in zip(prot.parents, prot.parents_chain_index ): parent_dict.setdefault(str(__UpperCAmelCase ), [] ) parent_dict[str(__UpperCAmelCase )].append(__UpperCAmelCase ) snake_case_ = max([int(__UpperCAmelCase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): snake_case_ = parent_dict.get(str(__UpperCAmelCase ), ['''N/A'''] ) parents_per_chain.append(__UpperCAmelCase ) else: parents_per_chain.append(list(prot.parents ) ) else: snake_case_ = [['''N/A''']] def make_parent_line(__UpperCAmelCase ) -> str: return F"PARENT {' '.join(__UpperCAmelCase )}" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) snake_case_ = 0 for i, l in enumerate(__UpperCAmelCase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(__UpperCAmelCase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(__UpperCAmelCase ): snake_case_ = parents_per_chain[chain_counter] else: snake_case_ = ['''N/A'''] out_pdb_lines.append(make_parent_line(__UpperCAmelCase ) ) return "\n".join(__UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' snake_case_ = residue_constants.restypes + ['''X'''] def res_atoa(__UpperCAmelCase ) -> str: return residue_constants.restype_atoa.get(restypes[r], '''UNK''' ) snake_case_ = residue_constants.atom_types snake_case_ = [] snake_case_ = prot.atom_mask snake_case_ = prot.aatype snake_case_ = prot.atom_positions snake_case_ = prot.residue_index.astype(np.intaa ) snake_case_ = prot.b_factors snake_case_ = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) snake_case_ = get_pdb_headers(__UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: pdb_lines.extend(__UpperCAmelCase ) snake_case_ = aatype.shape[0] snake_case_ = 1 snake_case_ = 0 snake_case_ = string.ascii_uppercase snake_case_ = None # Add all atom sites. for i in range(__UpperCAmelCase ): snake_case_ = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(__UpperCAmelCase, atom_positions[i], atom_mask[i], b_factors[i] ): if mask < 0.5: continue snake_case_ = '''ATOM''' snake_case_ = atom_name if len(__UpperCAmelCase ) == 4 else F" {atom_name}" snake_case_ = '''''' snake_case_ = '''''' snake_case_ = 1.0_0 snake_case_ = atom_name[0] # Protein supports only C, N, O, S, this works. snake_case_ = '''''' snake_case_ = '''A''' if chain_index is not None: snake_case_ = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! snake_case_ = ( F"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" F"{res_name_a:>3} {chain_tag:>1}" F"{residue_index[i]:>4}{insertion_code:>1} " F"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" F"{occupancy:>6.2f}{b_factor:>6.2f} " F"{element:>2}{charge:>2}" ) pdb_lines.append(__UpperCAmelCase ) atom_index += 1 snake_case_ = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: snake_case_ = True snake_case_ = chain_index[i + 1] if should_terminate: # Close the chain. snake_case_ = '''TER''' snake_case_ = ( F"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}" ) pdb_lines.append(__UpperCAmelCase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(__UpperCAmelCase, __UpperCAmelCase ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(__UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase ) -> np.ndarray: '''simple docstring''' return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase = None, __UpperCAmelCase = None, __UpperCAmelCase = None, __UpperCAmelCase = None, __UpperCAmelCase = None, ) -> Protein: '''simple docstring''' return Protein( aatype=features['''aatype'''], atom_positions=result['''final_atom_positions'''], atom_mask=result['''final_atom_mask'''], residue_index=features['''residue_index'''] + 1, b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ), chain_index=__UpperCAmelCase, remark=__UpperCAmelCase, parents=__UpperCAmelCase, parents_chain_index=__UpperCAmelCase, )
56
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A : Tuple = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Dict = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : str = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys A : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int = 1000 ) ->int: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 1, 1 _SCREAMING_SNAKE_CASE = [] for i in range(1 , n + 1 ): _SCREAMING_SNAKE_CASE = prev_numerator + 2 * prev_denominator _SCREAMING_SNAKE_CASE = prev_numerator + prev_denominator if len(str(__lowerCamelCase ) ) > len(str(__lowerCamelCase ) ): result.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = numerator _SCREAMING_SNAKE_CASE = denominator return len(__lowerCamelCase ) if __name__ == "__main__": print(f"""{solution() = }""")
58
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase = 6008_5147_5143 ): '''simple docstring''' try: __lowerCAmelCase = int(_UpperCamelCase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) __lowerCAmelCase = 2 __lowerCAmelCase = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 __lowerCAmelCase = i while n % i == 0: __lowerCAmelCase = n // i i += 1 return int(_UpperCamelCase ) if __name__ == "__main__": print(f'''{solution() = }''')
57
0
from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class UpperCAmelCase ( A_ ): def _SCREAMING_SNAKE_CASE (self : str ) -> List[Any]: '''simple docstring''' return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> Tuple: '''simple docstring''' snake_case : List[Any] = {"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]} return Dataset.from_dict(snake_case__ ) def _SCREAMING_SNAKE_CASE (self : int ) -> Union[str, Any]: '''simple docstring''' snake_case : Tuple = self._create_example_records() snake_case : Tuple = Dataset.from_list(snake_case__ ) self.assertListEqual(dset.column_names , ["col_1", "col_2"] ) for i, r in enumerate(snake_case__ ): self.assertDictEqual(snake_case__ , example_records[i] ) def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> Optional[Any]: '''simple docstring''' snake_case : Any = self._create_example_records() snake_case : Union[str, Any] = Dataset.from_list(snake_case__ ) snake_case : Tuple = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> str: # checks what happens with missing columns '''simple docstring''' snake_case : str = [{"col_1": 1}, {"col_2": "x"}] snake_case : str = Dataset.from_list(snake_case__ ) self.assertDictEqual(dset[0] , {"col_1": 1} ) self.assertDictEqual(dset[1] , {"col_1": None} ) # NB: first record is used for columns def _SCREAMING_SNAKE_CASE (self : str ) -> List[Any]: # checks if the type can be inferred from the second record '''simple docstring''' snake_case : Optional[Any] = [{"col_1": []}, {"col_1": [1, 2]}] snake_case : str = Dataset.from_list(snake_case__ ) self.assertEqual(dset.info.features["col_1"] , Sequence(Value("int64" ) ) ) def _SCREAMING_SNAKE_CASE (self : Union[str, Any] ) -> List[str]: '''simple docstring''' snake_case : List[Any] = Dataset.from_list([] ) self.assertEqual(len(snake_case__ ) , 0 ) self.assertListEqual(dset.column_names , [] )
59
"""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 _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__( self , __a , __a=None , __a=True , __a=None , **__a ): __lowerCAmelCase = parent __lowerCAmelCase = config_class __lowerCAmelCase = has_text_modality __lowerCAmelCase = kwargs __lowerCAmelCase = common_properties def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = ( ["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(__a , __a ) , msg=f"`{prop}` does not exist" ) # Test that config has the common properties as setter for idx, name in enumerate(__a ): try: setattr(__a , __a , __a ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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(__a ): try: __lowerCAmelCase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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 ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , __a ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , "config.json" ) config_first.to_json_file(__a ) __lowerCAmelCase = self.config_class.from_json_file(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = "test" with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , __a ) config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a , subfolder=__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) __lowerCAmelCase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def snake_case ( self ): if self.config_class.is_composition: return __lowerCAmelCase = self.config_class() self.parent.assertIsNotNone(__a ) def snake_case ( self ): __lowerCAmelCase = copy.deepcopy(__a ) __lowerCAmelCase = self.config_class(**__a ) __lowerCAmelCase = [] 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(__a , __a ) != value: wrong_values.append((key, getattr(__a , __a ), value) ) if len(__a ) > 0: __lowerCAmelCase = "\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 ): 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()
57
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case__ : Optional[int] = logging.get_logger(__name__) snake_case__ : List[Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class snake_case_( a__ ): __UpperCamelCase = '''data2vec-text''' def __init__( self : Optional[Any] , UpperCamelCase_ : List[str]=3_0_5_2_2 , UpperCamelCase_ : Union[str, Any]=7_6_8 , UpperCamelCase_ : List[str]=1_2 , UpperCamelCase_ : Optional[Any]=1_2 , UpperCamelCase_ : Optional[int]=3_0_7_2 , UpperCamelCase_ : List[str]="gelu" , UpperCamelCase_ : int=0.1 , UpperCamelCase_ : Optional[Any]=0.1 , UpperCamelCase_ : List[Any]=5_1_2 , UpperCamelCase_ : int=2 , UpperCamelCase_ : Optional[Any]=0.02 , UpperCamelCase_ : Tuple=1E-12 , UpperCamelCase_ : Any=1 , UpperCamelCase_ : Optional[Any]=0 , UpperCamelCase_ : int=2 , UpperCamelCase_ : Optional[Any]="absolute" , UpperCamelCase_ : Dict=True , UpperCamelCase_ : List[str]=None , **UpperCamelCase_ : List[Any] , ): super().__init__(pad_token_id=UpperCamelCase_ , bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ ) lowerCAmelCase : List[Any] = vocab_size lowerCAmelCase : List[str] = hidden_size lowerCAmelCase : Optional[Any] = num_hidden_layers lowerCAmelCase : str = num_attention_heads lowerCAmelCase : Any = hidden_act lowerCAmelCase : List[str] = intermediate_size lowerCAmelCase : Optional[int] = hidden_dropout_prob lowerCAmelCase : List[str] = attention_probs_dropout_prob lowerCAmelCase : Optional[Any] = max_position_embeddings lowerCAmelCase : int = type_vocab_size lowerCAmelCase : List[Any] = initializer_range lowerCAmelCase : List[str] = layer_norm_eps lowerCAmelCase : Dict = position_embedding_type lowerCAmelCase : Tuple = use_cache lowerCAmelCase : Union[str, Any] = classifier_dropout class snake_case_( a__ ): @property def lowerCamelCase__ ( self : Any ): if self.task == "multiple-choice": lowerCAmelCase : List[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowerCAmelCase : Optional[int] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
60
"""simple docstring""" A : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
57
0
"""simple docstring""" from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( """The RoBERTa Model transformer with early exiting (DeeRoBERTa). """ ,lowercase__ ,) class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = RobertaConfig SCREAMING_SNAKE_CASE__ : int = """roberta""" def __init__( self , lowercase_ ): """simple docstring""" super().__init__(lowercase_ ) UpperCAmelCase_ : int = RobertaEmbeddings(lowercase_ ) self.init_weights() @add_start_docstrings( """RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. """ ,lowercase__ ,) class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = RobertaConfig SCREAMING_SNAKE_CASE__ : Optional[int] = """roberta""" def __init__( self , lowercase_ ): """simple docstring""" super().__init__(lowercase_ ) UpperCAmelCase_ : Any = config.num_labels UpperCAmelCase_ : Optional[Any] = config.num_hidden_layers UpperCAmelCase_ : int = DeeRobertaModel(lowercase_ ) UpperCAmelCase_ : Tuple = nn.Dropout(config.hidden_dropout_prob ) UpperCAmelCase_ : Dict = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(lowercase_ ) def UpperCamelCase__ ( self , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=None , lowercase_=-1 , lowercase_=False , ): """simple docstring""" UpperCAmelCase_ : str = self.num_layers try: UpperCAmelCase_ : str = self.roberta( lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , position_ids=lowercase_ , head_mask=lowercase_ , inputs_embeds=lowercase_ , ) UpperCAmelCase_ : List[str] = outputs[1] UpperCAmelCase_ : Optional[Any] = self.dropout(lowercase_ ) UpperCAmelCase_ : List[str] = self.classifier(lowercase_ ) UpperCAmelCase_ : Tuple = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: UpperCAmelCase_ : Optional[int] = e.message UpperCAmelCase_ : Optional[Any] = e.exit_layer UpperCAmelCase_ : List[str] = outputs[0] if not self.training: UpperCAmelCase_ : Optional[int] = entropy(lowercase_ ) UpperCAmelCase_ : List[str] = [] UpperCAmelCase_ : Dict = [] if labels is not None: if self.num_labels == 1: # We are doing regression UpperCAmelCase_ : int = MSELoss() UpperCAmelCase_ : Union[str, Any] = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: UpperCAmelCase_ : Dict = CrossEntropyLoss() UpperCAmelCase_ : Any = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits UpperCAmelCase_ : List[str] = [] for highway_exit in outputs[-1]: UpperCAmelCase_ : int = highway_exit[0] if not self.training: highway_logits_all.append(lowercase_ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression UpperCAmelCase_ : str = MSELoss() UpperCAmelCase_ : Optional[Any] = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: UpperCAmelCase_ : List[Any] = CrossEntropyLoss() UpperCAmelCase_ : Union[str, Any] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(lowercase_ ) if train_highway: UpperCAmelCase_ : Tuple = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: UpperCAmelCase_ : Any = (loss,) + outputs if not self.training: UpperCAmelCase_ : Any = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: UpperCAmelCase_ : List[str] = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
61
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : str = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : str =["""input_ids""", """attention_mask"""] def __init__( self , __a="</s>" , __a="<unk>" , __a="<pad>" , __a=1_25 , __a=None , **__a , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __lowerCAmelCase = [f"<extra_id_{i}>" for i in range(__a )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __lowerCAmelCase = len(set(filter(lambda __a : bool("extra_id" in str(__a ) ) , __a ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the" " extra_ids tokens" ) __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else pad_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else eos_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else unk_token super().__init__( eos_token=__a , unk_token=__a , pad_token=__a , extra_ids=__a , additional_special_tokens=__a , **__a , ) __lowerCAmelCase = extra_ids __lowerCAmelCase = 2**8 # utf is 8 bits # define special tokens dict __lowerCAmelCase = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __lowerCAmelCase = len(self.special_tokens_encoder ) __lowerCAmelCase = len(__a ) for i, token in enumerate(__a ): __lowerCAmelCase = self.vocab_size + i - n __lowerCAmelCase = {v: k for k, v in self.special_tokens_encoder.items()} @property def snake_case ( self ): return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def snake_case ( self , __a , __a = None , __a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__a )) + [1] return ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] def snake_case ( self , __a ): if len(__a ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated" " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = self._add_eos_if_not_present(__a ) if token_ids_a is None: return token_ids_a else: __lowerCAmelCase = self._add_eos_if_not_present(__a ) return token_ids_a + token_ids_a def snake_case ( self , __a ): __lowerCAmelCase = [chr(__a ) for i in text.encode("utf-8" )] return tokens def snake_case ( self , __a ): if token in self.special_tokens_encoder: __lowerCAmelCase = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __lowerCAmelCase = self.added_tokens_encoder[token] elif len(__a ) != 1: __lowerCAmelCase = self.unk_token_id else: __lowerCAmelCase = ord(__a ) + self._num_special_tokens return token_id def snake_case ( self , __a ): if index in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[index] else: __lowerCAmelCase = chr(index - self._num_special_tokens ) return token def snake_case ( self , __a ): __lowerCAmelCase = B"" for token in tokens: if token in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.added_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.special_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) elif token in self.added_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) else: __lowerCAmelCase = bytes([ord(__a )] ) bstring += tok_string __lowerCAmelCase = bstring.decode("utf-8" , errors="ignore" ) return string def snake_case ( self , __a , __a = None ): return ()
57
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = "swinv2" UpperCAmelCase__ : Dict = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , A_=224 , A_=4 , A_=3 , A_=96 , A_=[2, 2, 6, 2] , A_=[3, 6, 12, 24] , A_=7 , A_=4.0 , A_=True , A_=0.0 , A_=0.0 , A_=0.1 , A_="gelu" , A_=False , A_=0.02 , A_=1E-5 , A_=32 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =embed_dim __UpperCamelCase =depths __UpperCamelCase =len(A_ ) __UpperCamelCase =num_heads __UpperCamelCase =window_size __UpperCamelCase =mlp_ratio __UpperCamelCase =qkv_bias __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =drop_path_rate __UpperCamelCase =hidden_act __UpperCamelCase =use_absolute_embeddings __UpperCamelCase =layer_norm_eps __UpperCamelCase =initializer_range __UpperCamelCase =encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __UpperCamelCase =int(embed_dim * 2 ** (len(A_ ) - 1) ) __UpperCamelCase =(0, 0, 0, 0)
62
"""simple docstring""" import numpy # List of input, output pairs A : Any = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) A : str = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) A : Union[str, Any] = [2, 4, 1, 5] A : int = len(train_data) A : Dict = 0.009 def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase="train" ): '''simple docstring''' return calculate_hypothesis_value(_UpperCamelCase , _UpperCamelCase ) - output( _UpperCamelCase , _UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(len(_UpperCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=m ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(_UpperCamelCase ): if index == -1: summation_value += _error(_UpperCamelCase ) else: summation_value += _error(_UpperCamelCase ) * train_data[i][0][index] return summation_value def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = summation_of_cost_derivative(_UpperCamelCase , _UpperCamelCase ) / m return cost_derivative_value def _lowerCamelCase ( ): '''simple docstring''' global parameter_vector # Tune these values to set a tolerance value for predicted output __lowerCAmelCase = 0.00_00_02 __lowerCAmelCase = 0 __lowerCAmelCase = 0 while True: j += 1 __lowerCAmelCase = [0, 0, 0, 0] for i in range(0 , len(_UpperCamelCase ) ): __lowerCAmelCase = get_cost_derivative(i - 1 ) __lowerCAmelCase = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( _UpperCamelCase , _UpperCamelCase , atol=_UpperCamelCase , rtol=_UpperCamelCase , ): break __lowerCAmelCase = temp_parameter_vector print(("Number of iterations:", j) ) def _lowerCamelCase ( ): '''simple docstring''' for i in range(len(_UpperCamelCase ) ): print(("Actual output value:", output(_UpperCamelCase , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(_UpperCamelCase , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
57
0
'''simple docstring''' from __future__ import annotations from typing import TypedDict class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =42 __a =42 def _lowerCamelCase ( lowercase : str ) -> list[str]: if not isinstance(lowercase , lowercase ): raise TypeError("The parameter s type must be str." ) return [s[i:] + s[:i] for i in range(len(lowercase ) )] def _lowerCamelCase ( lowercase : str ) -> BWTTransformDict: if not isinstance(lowercase , lowercase ): raise TypeError("The parameter s type must be str." ) if not s: raise ValueError("The parameter s must not be empty." ) _a = all_rotations(lowercase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(lowercase ), } return response def _lowerCamelCase ( lowercase : str , lowercase : int ) -> str: if not isinstance(lowercase , lowercase ): raise TypeError("The parameter bwt_string type must be str." ) if not bwt_string: raise ValueError("The parameter bwt_string must not be empty." ) try: _a = int(lowercase ) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0." ) if idx_original_string >= len(lowercase ): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) _a = [""] * len(lowercase ) for _ in range(len(lowercase ) ): for i in range(len(lowercase ) ): _a = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCAmelCase_ : str = 'Provide a string that I will generate its BWT transform: ' lowerCAmelCase_ : List[str] = input(entry_msg).strip() lowerCAmelCase_ : List[str] = bwt_transform(s) print( f"""Burrows Wheeler transform for string '{s}' results """ f"""in '{result['bwt_string']}'""" ) lowerCAmelCase_ : Optional[Any] = reverse_bwt(result['bwt_string'], result['idx_original_string']) print( f"""Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' """ f"""we get original string '{original_string}'""" )
63
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): __lowerCAmelCase = tempfile.mkdtemp() __lowerCAmelCase = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "的", "价", "格", "是", "15", "便", "alex", "##andra", ",", "。", "-", "t", "shirt", ] __lowerCAmelCase = 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] ) ) __lowerCAmelCase = { "do_resize": True, "size": {"height": 2_24, "width": 2_24}, "do_center_crop": True, "crop_size": {"height": 18, "width": 18}, "do_normalize": True, "image_mean": [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], "image_std": [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], "do_convert_rgb": True, } __lowerCAmelCase = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(__a , __a ) def snake_case ( self , **__a ): return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return BertTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self ): shutil.rmtree(self.tmpdirname ) def snake_case ( self ): __lowerCAmelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCAmelCase = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self ): __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__a ) __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __a ) self.assertIsInstance(processor_fast.tokenizer , __a ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __a ) self.assertIsInstance(processor_fast.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase = self.get_tokenizer(cls_token="(CLS)" , sep_token="(SEP)" ) __lowerCAmelCase = self.get_image_processor(do_normalize=__a ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="(CLS)" , sep_token="(SEP)" , do_normalize=__a ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = image_processor(__a , return_tensors="np" ) __lowerCAmelCase = processor(images=__a , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = processor(text=__a ) __lowerCAmelCase = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(__a ): processor() def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase = processor.batch_decode(__a ) __lowerCAmelCase = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
57
0
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs A_ = imread(r'''digital_image_processing/image_data/lena_small.jpg''') A_ = cvtColor(img, COLOR_BGR2GRAY) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Dict = cn.convert_to_negative(snake_case__ ) # assert negative_img array for at least one True assert negative_img.any() def UpperCAmelCase__ (): """simple docstring""" with Image.open("""digital_image_processing/image_data/lena_small.jpg""" ) as img: # Work around assertion for response assert str(cc.change_contrast(snake_case__ , 1_10 ) ).startswith( """<PIL.Image.Image image mode=RGB size=100x100 at""" ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : List[Any] = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Optional[int] = imread("""digital_image_processing/image_data/lena_small.jpg""" , 0 ) # assert ambiguous array for all == True assert canny_img.all() _snake_case : Optional[Any] = canny.canny(snake_case__ ) # assert canny array for at least one True assert canny_array.any() def UpperCAmelCase__ (): """simple docstring""" assert gg.gaussian_filter(snake_case__ , 5 , sigma=0.9 ).all() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) _snake_case : Optional[int] = conv.img_convolve(snake_case__ , snake_case__ ).astype(snake_case__ ) assert res.any() def UpperCAmelCase__ (): """simple docstring""" assert med.median_filter(snake_case__ , 3 ).any() def UpperCAmelCase__ (): """simple docstring""" _snake_case , _snake_case : int = sob.sobel_filter(snake_case__ ) assert grad.any() and theta.any() def UpperCAmelCase__ (): """simple docstring""" _snake_case : str = sp.make_sepia(snake_case__ , 20 ) assert sepia.all() def UpperCAmelCase__ (snake_case__ : str = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" _snake_case : Any = bs.Burkes(imread(snake_case__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def UpperCAmelCase__ (snake_case__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" _snake_case : Optional[Any] = rs.NearestNeighbour(imread(snake_case__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Union[str, Any] = """digital_image_processing/image_data/lena.jpg""" # Reading the image and converting it to grayscale. _snake_case : List[Any] = imread(snake_case__ , 0 ) # Test for get_neighbors_pixel function() return not None _snake_case : str = 0 _snake_case : Union[str, Any] = 0 _snake_case : Optional[int] = image[x_coordinate][y_coordinate] _snake_case : str = lbp.get_neighbors_pixel( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image _snake_case : Tuple = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): _snake_case : Optional[int] = lbp.local_binary_value(snake_case__ , snake_case__ , snake_case__ ) assert lbp_image.any()
64
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( _UpperCamelCase = 4 ): '''simple docstring''' __lowerCAmelCase = abs(_UpperCamelCase ) or 4 return [[1 + x + y * row_size for x in range(_UpperCamelCase )] for y in range(_UpperCamelCase )] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(reverse_column(_UpperCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_column(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [list(_UpperCamelCase ) for x in zip(*_UpperCamelCase )] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = matrix[::-1] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [x[::-1] for x in matrix] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for i in matrix: print(*_UpperCamelCase ) if __name__ == "__main__": A : Dict = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_aa(matrix)) A : List[str] = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_aaa(matrix)) A : str = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_aaa(matrix))
57
0
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase_ ( __A, __A=False ) -> List[str]: '''simple docstring''' UpperCAmelCase__ = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith("head" ): UpperCAmelCase__ = "segformer.encoder." + key if key.startswith("backbone" ): UpperCAmelCase__ = key.replace("backbone", "segformer.encoder" ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 UpperCAmelCase__ = key[key.find("patch_embed" ) + len("patch_embed" )] UpperCAmelCase__ = key.replace(f"""patch_embed{idx}""", f"""patch_embeddings.{int(__A )-1}""" ) if "norm" in key: UpperCAmelCase__ = key.replace("norm", "layer_norm" ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 UpperCAmelCase__ = key[key.find("segformer.encoder.layer_norm" ) + len("segformer.encoder.layer_norm" )] UpperCAmelCase__ = key.replace(f"""layer_norm{idx}""", f"""layer_norm.{int(__A )-1}""" ) if "layer_norm1" in key: UpperCAmelCase__ = key.replace("layer_norm1", "layer_norm_1" ) if "layer_norm2" in key: UpperCAmelCase__ = key.replace("layer_norm2", "layer_norm_2" ) if "block" in key: # replace for example block1 by block.0 UpperCAmelCase__ = key[key.find("block" ) + len("block" )] UpperCAmelCase__ = key.replace(f"""block{idx}""", f"""block.{int(__A )-1}""" ) if "attn.q" in key: UpperCAmelCase__ = key.replace("attn.q", "attention.self.query" ) if "attn.proj" in key: UpperCAmelCase__ = key.replace("attn.proj", "attention.output.dense" ) if "attn" in key: UpperCAmelCase__ = key.replace("attn", "attention.self" ) if "fc1" in key: UpperCAmelCase__ = key.replace("fc1", "dense1" ) if "fc2" in key: UpperCAmelCase__ = key.replace("fc2", "dense2" ) if "linear_pred" in key: UpperCAmelCase__ = key.replace("linear_pred", "classifier" ) if "linear_fuse" in key: UpperCAmelCase__ = key.replace("linear_fuse.conv", "linear_fuse" ) UpperCAmelCase__ = key.replace("linear_fuse.bn", "batch_norm" ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 UpperCAmelCase__ = key[key.find("linear_c" ) + len("linear_c" )] UpperCAmelCase__ = key.replace(f"""linear_c{idx}""", f"""linear_c.{int(__A )-1}""" ) if key.startswith("head" ): UpperCAmelCase__ = key.replace("head", "classifier" ) UpperCAmelCase__ = value return new_state_dict def lowerCAmelCase_ ( __A, __A ) -> Any: '''simple docstring''' for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) UpperCAmelCase__ = state_dict.pop(f"""segformer.encoder.block.{i}.{j}.attention.self.kv.weight""" ) UpperCAmelCase__ = state_dict.pop(f"""segformer.encoder.block.{i}.{j}.attention.self.kv.bias""" ) # next, add keys and values (in that order) to the state dict UpperCAmelCase__ = kv_weight[ : config.hidden_sizes[i], : ] UpperCAmelCase__ = kv_bias[: config.hidden_sizes[i]] UpperCAmelCase__ = kv_weight[ config.hidden_sizes[i] :, : ] UpperCAmelCase__ = kv_bias[ config.hidden_sizes[i] : ] def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase__ = Image.open(requests.get(__A, stream=__A ).raw ) return image @torch.no_grad() def lowerCAmelCase_ ( __A, __A, __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = SegformerConfig() UpperCAmelCase__ = False # set attributes based on model_name UpperCAmelCase__ = "huggingface/label-files" if "segformer" in model_name: UpperCAmelCase__ = model_name[len("segformer." ) : len("segformer." ) + 2] if "ade" in model_name: UpperCAmelCase__ = 150 UpperCAmelCase__ = "ade20k-id2label.json" UpperCAmelCase__ = (1, 150, 128, 128) elif "city" in model_name: UpperCAmelCase__ = 19 UpperCAmelCase__ = "cityscapes-id2label.json" UpperCAmelCase__ = (1, 19, 128, 128) else: raise ValueError(f"""Model {model_name} not supported""" ) elif "mit" in model_name: UpperCAmelCase__ = True UpperCAmelCase__ = model_name[4:6] UpperCAmelCase__ = 1_000 UpperCAmelCase__ = "imagenet-1k-id2label.json" UpperCAmelCase__ = (1, 1_000) else: raise ValueError(f"""Model {model_name} not supported""" ) # set config attributes UpperCAmelCase__ = json.load(open(hf_hub_download(__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()} if size == "b0": pass elif size == "b1": UpperCAmelCase__ = [64, 128, 320, 512] UpperCAmelCase__ = 256 elif size == "b2": UpperCAmelCase__ = [64, 128, 320, 512] UpperCAmelCase__ = 768 UpperCAmelCase__ = [3, 4, 6, 3] elif size == "b3": UpperCAmelCase__ = [64, 128, 320, 512] UpperCAmelCase__ = 768 UpperCAmelCase__ = [3, 4, 18, 3] elif size == "b4": UpperCAmelCase__ = [64, 128, 320, 512] UpperCAmelCase__ = 768 UpperCAmelCase__ = [3, 8, 27, 3] elif size == "b5": UpperCAmelCase__ = [64, 128, 320, 512] UpperCAmelCase__ = 768 UpperCAmelCase__ = [3, 6, 40, 3] else: raise ValueError(f"""Size {size} not supported""" ) # load image processor (only resize + normalize) UpperCAmelCase__ = SegformerImageProcessor( image_scale=(512, 512), keep_ratio=__A, align=__A, do_random_crop=__A ) # prepare image UpperCAmelCase__ = prepare_img() UpperCAmelCase__ = image_processor(images=__A, return_tensors="pt" ).pixel_values logger.info(f"""Converting model {model_name}...""" ) # load original state dict if encoder_only: UpperCAmelCase__ = torch.load(__A, map_location=torch.device("cpu" ) ) else: UpperCAmelCase__ = torch.load(__A, map_location=torch.device("cpu" ) )["state_dict"] # rename keys UpperCAmelCase__ = rename_keys(__A, encoder_only=__A ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(__A, __A ) # create HuggingFace model and load state dict if encoder_only: UpperCAmelCase__ = False UpperCAmelCase__ = SegformerForImageClassification(__A ) else: UpperCAmelCase__ = SegformerForSemanticSegmentation(__A ) model.load_state_dict(__A ) model.eval() # forward pass UpperCAmelCase__ = model(__A ) UpperCAmelCase__ = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": UpperCAmelCase__ = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": UpperCAmelCase__ = torch.tensor( [ [[-7.5820, -8.7231, -8.3215], [-8.0600, -10.3529, -10.0304], [-7.5208, -9.4103, -9.6239]], [[-12.6918, -13.8994, -13.7137], [-13.3196, -15.7523, -15.4789], [-12.9343, -14.8757, -14.9689]], [[-11.1911, -11.9421, -11.3243], [-11.3342, -13.6839, -13.3581], [-10.3909, -12.1832, -12.4858]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": UpperCAmelCase__ = torch.tensor( [ [[-11.8173, -14.3850, -16.3128], [-14.5648, -16.5804, -18.6568], [-14.7223, -15.7387, -18.4218]], [[-15.7290, -17.9171, -19.4423], [-18.3105, -19.9448, -21.4661], [-17.9296, -18.6497, -20.7910]], [[-15.0783, -17.0336, -18.2789], [-16.8771, -18.6870, -20.1612], [-16.2454, -17.1426, -19.5055]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": UpperCAmelCase__ = torch.tensor( [ [[-9.0878, -10.2081, -10.1891], [-9.3144, -10.7941, -10.9843], [-9.2294, -10.3855, -10.5704]], [[-12.2316, -13.9068, -13.6102], [-12.9161, -14.3702, -14.3235], [-12.5233, -13.7174, -13.7932]], [[-14.6275, -15.2490, -14.9727], [-14.3400, -15.9687, -16.2827], [-14.1484, -15.4033, -15.8937]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": UpperCAmelCase__ = torch.tensor( [ [[-12.3144, -13.2447, -14.0802], [-13.3614, -14.5816, -15.6117], [-13.3340, -14.4433, -16.2219]], [[-19.2781, -20.4128, -20.7506], [-20.6153, -21.6566, -22.0998], [-19.9800, -21.0430, -22.1494]], [[-18.8739, -19.7804, -21.1834], [-20.1233, -21.6765, -23.2944], [-20.0315, -21.2641, -23.6944]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": UpperCAmelCase__ = torch.tensor( [ [[-9.5524, -12.0835, -11.7348], [-10.5229, -13.6446, -14.5662], [-9.5842, -12.8851, -13.9414]], [[-15.3432, -17.5323, -17.0818], [-16.3330, -18.9255, -19.2101], [-15.1340, -17.7848, -18.3971]], [[-12.6072, -14.9486, -14.6631], [-13.7629, -17.0907, -17.7745], [-12.7899, -16.1695, -17.1671]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-11.9295, -13.4057, -14.8106], [-13.3431, -14.8179, -15.3781], [-14.2836, -15.5942, -16.1588]], [[-11.4906, -12.8067, -13.6564], [-13.1189, -14.0500, -14.1543], [-13.8748, -14.5136, -14.8789]], [[0.5374, 0.1067, -0.4742], [0.1141, -0.2255, -0.7099], [-0.3000, -0.5924, -1.3105]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-7.8217, -9.8767, -10.1717], [-9.4438, -10.9058, -11.4047], [-9.7939, -12.3495, -12.1079]], [[-7.1514, -9.5336, -10.0860], [-9.7776, -11.6822, -11.8439], [-10.1411, -12.7655, -12.8972]], [[0.3021, 0.0805, -0.2310], [-0.0328, -0.1605, -0.2714], [-0.1408, -0.5477, -0.6976]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": UpperCAmelCase__ = torch.tensor( [ [ [-1.1_372e01, -1.2_787e01, -1.3_477e01], [-1.2_536e01, -1.4_194e01, -1.4_409e01], [-1.3_217e01, -1.4_888e01, -1.5_327e01], ], [ [-1.4_791e01, -1.7_122e01, -1.8_277e01], [-1.7_163e01, -1.9_192e01, -1.9_533e01], [-1.7_897e01, -1.9_991e01, -2.0_315e01], ], [ [7.6_723e-01, 4.1_921e-01, -7.7_878e-02], [4.7_772e-01, 9.5_557e-03, -2.8_082e-01], [3.6_032e-01, -2.4_826e-01, -5.1_168e-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-9.4959, -11.3087, -11.7479], [-11.0025, -12.6540, -12.3319], [-11.4064, -13.0487, -12.9905]], [[-9.8905, -11.3084, -12.0854], [-11.1726, -12.7698, -12.9583], [-11.5985, -13.3278, -14.1774]], [[0.2213, 0.0192, -0.2466], [-0.1731, -0.4213, -0.4874], [-0.3126, -0.6541, -1.1389]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-16.0976, -16.4856, -17.3962], [-16.6234, -19.0342, -19.7685], [-16.0900, -18.0661, -19.1180]], [[-18.4750, -18.8488, -19.5074], [-19.4030, -22.1570, -22.5977], [-19.1191, -20.8486, -22.3783]], [[-4.5178, -5.5037, -6.5109], [-5.0884, -7.2174, -8.0334], [-4.4156, -5.8117, -7.2970]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-14.2081, -14.4732, -14.1977], [-14.5867, -16.4423, -16.6356], [-13.4441, -14.9685, -16.8696]], [[-14.4576, -14.7073, -15.0451], [-15.0816, -17.6237, -17.9873], [-14.4213, -16.0199, -18.5992]], [[-4.7349, -4.9588, -5.0966], [-4.3210, -6.9325, -7.2591], [-3.4312, -4.7484, -7.1917]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-11.7737, -11.9526, -11.3273], [-13.6692, -14.4574, -13.8878], [-13.8937, -14.6924, -15.9345]], [[-14.6706, -14.5330, -14.1306], [-16.1502, -16.8180, -16.4269], [-16.8338, -17.8939, -20.1746]], [[1.0491, 0.8289, 1.0310], [1.1044, 0.5219, 0.8055], [1.0899, 0.6926, 0.5590]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": UpperCAmelCase__ = torch.tensor( [ [[-12.5641, -13.4777, -13.0684], [-13.9587, -15.8983, -16.6557], [-13.3109, -15.7350, -16.3141]], [[-14.7074, -15.4352, -14.5944], [-16.6353, -18.1663, -18.6120], [-15.1702, -18.0329, -18.1547]], [[-1.7990, -2.0951, -1.7784], [-2.6397, -3.8245, -3.9686], [-1.5264, -2.8126, -2.9316]], ] ) else: UpperCAmelCase__ = logits.argmax(-1 ).item() print("Predicted class:", model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3], __A, atol=1e-2 ) # finally, save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(__A ).mkdir(exist_ok=__A ) model.save_pretrained(__A ) image_processor.save_pretrained(__A ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='segformer.b0.512x512.ade.160k', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) UpperCamelCase__ = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
65
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCAmelCase : Union[str, Any] =TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = TextaTextGenerationPipeline(model=__a , tokenizer=__a ) return generator, ["Something to write", "Something else"] def snake_case ( self , __a , __a ): __lowerCAmelCase = generator("Something there" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["generated_text"].startswith("Something there" ) ) __lowerCAmelCase = generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) __lowerCAmelCase = generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) with self.assertRaises(__a ): generator(4 ) @require_torch def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="pt" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] ) __lowerCAmelCase = 3 __lowerCAmelCase = generator( "Something there" , num_return_sequences=__a , num_beams=__a , ) __lowerCAmelCase = [ {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": ""}, ] self.assertEqual(__a , __a ) __lowerCAmelCase = generator("This is a test" , do_sample=__a , num_return_sequences=2 , return_tensors=__a ) self.assertEqual( __a , [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ] , ) __lowerCAmelCase = generator.model.config.eos_token_id __lowerCAmelCase = "<pad>" __lowerCAmelCase = generator( ["This is a test", "This is a second test"] , do_sample=__a , num_return_sequences=2 , batch_size=2 , return_tensors=__a , ) self.assertEqual( __a , [ [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], ] , ) @require_tf def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="tf" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] )
57
0
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging __a = logging.get_logger(__name__) __a = { "EleutherAI/gpt-j-6B": "https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' _A : List[Any] = """gptj""" _A : Union[str, Any] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self: int , snake_case: int=50_400 , snake_case: Optional[Any]=2_048 , snake_case: Any=4_096 , snake_case: Dict=28 , snake_case: Union[str, Any]=16 , snake_case: Optional[int]=64 , snake_case: List[Any]=None , snake_case: List[str]="gelu_new" , snake_case: Dict=0.0 , snake_case: Union[str, Any]=0.0 , snake_case: List[Any]=0.0 , snake_case: List[Any]=1E-5 , snake_case: Any=0.0_2 , snake_case: Union[str, Any]=True , snake_case: int=50_256 , snake_case: int=50_256 , snake_case: List[Any]=False , **snake_case: List[str] , ) -> Optional[Any]: snake_case_ :Optional[Any] = vocab_size snake_case_ :List[Any] = n_positions snake_case_ :List[str] = n_embd snake_case_ :List[str] = n_layer snake_case_ :int = n_head snake_case_ :int = n_inner snake_case_ :List[str] = rotary_dim snake_case_ :Optional[Any] = activation_function snake_case_ :int = resid_pdrop snake_case_ :List[str] = embd_pdrop snake_case_ :str = attn_pdrop snake_case_ :Union[str, Any] = layer_norm_epsilon snake_case_ :Optional[Any] = initializer_range snake_case_ :Any = use_cache snake_case_ :Tuple = bos_token_id snake_case_ :Any = eos_token_id super().__init__( bos_token_id=snake_case , eos_token_id=snake_case , tie_word_embeddings=snake_case , **snake_case ) class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' def __init__( self: int , snake_case: PretrainedConfig , snake_case: str = "default" , snake_case: List[PatchingSpec] = None , snake_case: bool = False , ) -> Any: super().__init__(snake_case , task=snake_case , patching_specs=snake_case , use_past=snake_case ) if not getattr(self._config , """pad_token_id""" , snake_case ): # TODO: how to do that better? snake_case_ :Optional[Any] = 0 @property def lowerCAmelCase_ ( self: Optional[int] ) -> Mapping[str, Mapping[int, str]]: snake_case_ :Tuple = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(snake_case , direction="""inputs""" ) snake_case_ :Optional[Any] = {0: """batch""", 1: """past_sequence + sequence"""} else: snake_case_ :Tuple = {0: """batch""", 1: """sequence"""} return common_inputs @property def lowerCAmelCase_ ( self: Tuple ) -> int: return self._config.n_layer @property def lowerCAmelCase_ ( self: Optional[int] ) -> int: return self._config.n_head def lowerCAmelCase_ ( self: int , snake_case: PreTrainedTokenizer , snake_case: int = -1 , snake_case: int = -1 , snake_case: bool = False , snake_case: Optional[TensorType] = None , ) -> Mapping[str, Any]: snake_case_ :Tuple = super(snake_case , self ).generate_dummy_inputs( snake_case , batch_size=snake_case , seq_length=snake_case , is_pair=snake_case , framework=snake_case ) # We need to order the input in the way they appears in the forward() snake_case_ :int = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch snake_case_, snake_case_ :List[str] = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values snake_case_ :Dict = seqlen + 2 snake_case_ :List[Any] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) snake_case_ :Optional[int] = [ (torch.zeros(snake_case ), torch.zeros(snake_case )) for _ in range(self.num_layers ) ] snake_case_ :Dict = common_inputs["""attention_mask"""] if self.use_past: snake_case_ :Optional[int] = ordered_inputs["""attention_mask"""].dtype snake_case_ :List[str] = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(snake_case , snake_case , dtype=snake_case )] , dim=1 ) return ordered_inputs @property def lowerCAmelCase_ ( self: List[str] ) -> int: return 13
66
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class _UpperCamelCase ( pl.LightningModule ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCAmelCase = model __lowerCAmelCase = 2 __lowerCAmelCase = nn.Linear(self.model.config.hidden_size , self.num_labels ) def snake_case ( self ): pass def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = LongformerModel.from_pretrained(_UpperCamelCase ) __lowerCAmelCase = LightningModel(_UpperCamelCase ) __lowerCAmelCase = torch.load(_UpperCamelCase , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model __lowerCAmelCase = LongformerForQuestionAnswering.from_pretrained(_UpperCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(_UpperCamelCase ) print(f"Conversion successful. Model saved under {pytorch_dump_folder_path}" ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--longformer_model", default=None, type=str, required=True, help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.", ) parser.add_argument( "--longformer_question_answering_ckpt_path", default=None, type=str, required=True, help="Path the official PyTorch Lightning Checkpoint.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) A : Optional[int] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
57
0
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> bool: return str(UpperCamelCase__ ) == str(UpperCamelCase__ )[::-1] def __lowerCAmelCase ( UpperCamelCase__ ) -> int: return int(UpperCamelCase__ ) + int(str(UpperCamelCase__ )[::-1] ) def __lowerCAmelCase ( UpperCamelCase__ = 1_00_00 ) -> int: __lowerCamelCase = [] for num in range(1 , UpperCamelCase__ ): __lowerCamelCase = 0 __lowerCamelCase = num while iterations < 50: __lowerCamelCase = sum_reverse(UpperCamelCase__ ) iterations += 1 if is_palindrome(UpperCamelCase__ ): break else: lychrel_nums.append(UpperCamelCase__ ) return len(UpperCamelCase__ ) if __name__ == "__main__": print(f'{solution() = }')
67
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = False while is_sorted is False: # Until all the indices are traversed keep looping __lowerCAmelCase = True for i in range(0 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False for i in range(1 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False return input_list if __name__ == "__main__": print("Enter list to be sorted") A : Union[str, Any] = [int(x) for x in input().split()] # inputing elements of the list in one line A : str = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
57
0
from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class a__ : """simple docstring""" def __init__( self , lowercase , ) -> List[Any]: '''simple docstring''' A__ = parent A__ = 13 A__ = 7 A__ = True A__ = True A__ = False A__ = True A__ = 99 A__ = 32 A__ = 2 A__ = 4 A__ = 37 A__ = "gelu" A__ = 0.1 A__ = 0.1 A__ = 512 A__ = 16 A__ = 2 A__ = 0.02 A__ = 3 A__ = 4 A__ = None def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length] ) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ = ids_tensor([self.batch_size] , self.num_choices ) A__ = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' A__ = TFDistilBertModel(config=lowercase ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase ) A__ = [input_ids, input_mask] A__ = 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 , lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = TFDistilBertForMaskedLM(config=lowercase ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> str: '''simple docstring''' A__ = TFDistilBertForQuestionAnswering(config=lowercase ) A__ = { "input_ids": input_ids, "attention_mask": input_mask, } A__ = model(lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> List[str]: '''simple docstring''' A__ = self.num_labels A__ = TFDistilBertForSequenceClassification(lowercase ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' A__ = self.num_choices A__ = TFDistilBertForMultipleChoice(lowercase ) A__ = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) A__ = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) A__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, } A__ = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' A__ = self.num_labels A__ = TFDistilBertForTokenClassification(lowercase ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.prepare_config_and_inputs() ((A__) , (A__) , (A__) , (A__) , (A__) , (A__)) = config_and_inputs A__ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __lowerCamelCase = ( { 'feature-extraction': TFDistilBertModel, 'fill-mask': TFDistilBertForMaskedLM, 'question-answering': TFDistilBertForQuestionAnswering, 'text-classification': TFDistilBertForSequenceClassification, 'token-classification': TFDistilBertForTokenClassification, 'zero-shot': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = TFDistilBertModelTester(self ) A__ = ConfigTester(self , config_class=lowercase , dim=37 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) @slow def UpperCamelCase ( self ) -> str: '''simple docstring''' for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): A__ = TFDistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_tf class a__ ( unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = TFDistilBertModel.from_pretrained("distilbert-base-uncased" ) A__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) A__ = model(lowercase )[0] A__ = [1, 6, 768] self.assertEqual(output.shape , lowercase ) A__ = tf.constant( [ [ [0.1926_1885, -0.1373_2955, 0.411_9799], [0.2215_0156, -0.0742_2661, 0.3903_7204], [0.2275_6018, -0.089_6414, 0.370_1467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1e-4 )
68
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =["""image_processor""", """tokenizer"""] __UpperCAmelCase : Optional[Any] ="""CLIPImageProcessor""" __UpperCAmelCase : Union[str, Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): __lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) __lowerCAmelCase = kwargs.pop("feature_extractor" ) __lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self , __a=None , __a=None , __a=None , **__a ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __lowerCAmelCase = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: __lowerCAmelCase = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: __lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): __lowerCAmelCase = self.tokenizer.model_input_names __lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
57
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor __UpperCamelCase = logging.get_logger(__name__) class UpperCamelCase ( lowerCAmelCase__ ): def __init__( self, *lowerCAmelCase__, **lowerCAmelCase__) -> None: warnings.warn( 'The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use OwlViTImageProcessor instead.', lowerCAmelCase__, ) super().__init__(*lowerCAmelCase__, **lowerCAmelCase__)
69
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class _UpperCamelCase : '''simple docstring''' pass
57
0
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase : def __init__( self : List[str] , __snake_case : str , __snake_case : Dict=12 , __snake_case : Dict=7 , __snake_case : str=True , __snake_case : List[Any]=True , __snake_case : Dict=True , __snake_case : Optional[int]=99 , __snake_case : Dict=32 , __snake_case : Optional[Any]=32 , __snake_case : Union[str, Any]=2 , __snake_case : List[str]=4 , __snake_case : Optional[int]=37 , __snake_case : Union[str, Any]=0.1 , __snake_case : Optional[int]=0.1 , __snake_case : int=5_12 , __snake_case : List[Any]=0.02 , __snake_case : Any=0 , __snake_case : List[Any]=None , ) -> int: _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = seq_length _lowerCAmelCase = is_training _lowerCAmelCase = use_input_mask _lowerCAmelCase = use_labels _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = projection_dim _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = intermediate_size _lowerCAmelCase = dropout _lowerCAmelCase = attention_dropout _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = initializer_range _lowerCAmelCase = scope _lowerCAmelCase = bos_token_id def lowercase__ ( self : List[Any] ) -> List[str]: _lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCAmelCase = None if self.use_input_mask: _lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: _lowerCAmelCase = input_mask.numpy() _lowerCAmelCase , _lowerCAmelCase = input_mask.shape _lowerCAmelCase = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__snake_case ): _lowerCAmelCase = 1 _lowerCAmelCase = 0 _lowerCAmelCase = self.get_config() return config, input_ids, tf.convert_to_tensor(__snake_case ) def lowercase__ ( self : List[str] ) -> Optional[int]: return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def lowercase__ ( self : int , __snake_case : Any , __snake_case : List[str] , __snake_case : List[Any] ) -> Optional[int]: _lowerCAmelCase = TFBlipTextModel(config=__snake_case ) _lowerCAmelCase = model(__snake_case , attention_mask=__snake_case , training=__snake_case ) _lowerCAmelCase = model(__snake_case , training=__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowercase__ ( self : Optional[int] ) -> Any: _lowerCAmelCase = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = config_and_inputs _lowerCAmelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCAmelCase ( snake_case_ , unittest.TestCase ): _lowercase: str = (TFBlipTextModel,) if is_tf_available() else () _lowercase: Dict = False _lowercase: Dict = False _lowercase: Dict = False def lowercase__ ( self : List[Any] ) -> Optional[int]: _lowerCAmelCase = BlipTextModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase__ ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def lowercase__ ( self : int ) -> List[str]: _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def lowercase__ ( self : str ) -> Union[str, Any]: pass def lowercase__ ( self : Optional[Any] ) -> Tuple: pass @unittest.skip(reason="""Blip does not use inputs_embeds""" ) def lowercase__ ( self : List[Any] ) -> List[Any]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def lowercase__ ( self : List[Any] ) -> List[str]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def lowercase__ ( self : List[str] ) -> int: pass @slow def lowercase__ ( self : List[str] ) -> List[str]: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase = TFBlipTextModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) def lowercase__ ( self : List[str] , __snake_case : List[str]=True ) -> Any: super().test_pt_tf_model_equivalence(allow_missing_keys=__snake_case )
70
"""simple docstring""" import sys from collections import defaultdict class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): return self.node_position[vertex] def snake_case ( self , __a , __a ): __lowerCAmelCase = pos def snake_case ( self , __a , __a , __a , __a ): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCAmelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCAmelCase = 2 * start + 1 else: __lowerCAmelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCAmelCase , __lowerCAmelCase = heap[smallest_child], positions[smallest_child] __lowerCAmelCase , __lowerCAmelCase = ( heap[start], positions[start], ) __lowerCAmelCase , __lowerCAmelCase = temp, tempa __lowerCAmelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __a ) self.top_to_bottom(__a , __a , __a , __a ) def snake_case ( self , __a , __a , __a , __a ): __lowerCAmelCase = position[index] while index != 0: __lowerCAmelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCAmelCase = heap[parent] __lowerCAmelCase = position[parent] self.set_position(position[parent] , __a ) else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , __a ) break __lowerCAmelCase = parent else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , 0 ) def snake_case ( self , __a , __a ): __lowerCAmelCase = len(__a ) // 2 - 1 for i in range(__a , -1 , -1 ): self.top_to_bottom(__a , __a , len(__a ) , __a ) def snake_case ( self , __a , __a ): __lowerCAmelCase = positions[0] __lowerCAmelCase = sys.maxsize self.top_to_bottom(__a , 0 , len(__a ) , __a ) return temp def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = Heap() __lowerCAmelCase = [0] * len(_UpperCamelCase ) __lowerCAmelCase = [-1] * len(_UpperCamelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCAmelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCAmelCase = [] for vertex in range(len(_UpperCamelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_UpperCamelCase ) heap.node_position.append(_UpperCamelCase ) __lowerCAmelCase = [] __lowerCAmelCase = 1 __lowerCAmelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCAmelCase = 0 __lowerCAmelCase = distance heap.heapify(_UpperCamelCase , _UpperCamelCase ) for _ in range(1 , len(_UpperCamelCase ) ): __lowerCAmelCase = heap.delete_minimum(_UpperCamelCase , _UpperCamelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCAmelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_UpperCamelCase )] ): __lowerCAmelCase = distance heap.bottom_to_top( _UpperCamelCase , heap.get_position(_UpperCamelCase ) , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A : Optional[Any] = int(input("Enter number of edges: ").strip()) A : Dict = defaultdict(list) for _ in range(edges_number): A : str = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
57
0
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class __A : """simple docstring""" UpperCamelCase__ : int =XGLMConfig UpperCamelCase__ : Optional[Any] ={} UpperCamelCase__ : List[str] ="""gelu""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=14 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=99 , lowerCamelCase__=32 , lowerCamelCase__=2 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=0.02 , ): """simple docstring""" __UpperCamelCase : Tuple =parent __UpperCamelCase : List[str] =batch_size __UpperCamelCase : str =seq_length __UpperCamelCase : Dict =is_training __UpperCamelCase : Tuple =use_input_mask __UpperCamelCase : List[Any] =use_labels __UpperCamelCase : Any =vocab_size __UpperCamelCase : List[Any] =d_model __UpperCamelCase : Optional[int] =num_hidden_layers __UpperCamelCase : List[str] =num_attention_heads __UpperCamelCase : Optional[int] =ffn_dim __UpperCamelCase : str =activation_function __UpperCamelCase : Any =activation_dropout __UpperCamelCase : Optional[int] =attention_dropout __UpperCamelCase : Optional[int] =max_position_embeddings __UpperCamelCase : Any =initializer_range __UpperCamelCase : Dict =None __UpperCamelCase : Optional[int] =0 __UpperCamelCase : Optional[Any] =2 __UpperCamelCase : str =1 def __lowercase ( self ): """simple docstring""" return XGLMConfig.from_pretrained('facebook/xglm-564M' ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[Any] =tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) __UpperCamelCase : Union[str, Any] =None if self.use_input_mask: __UpperCamelCase : Dict =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase : Any =self.get_config() __UpperCamelCase : Optional[Any] =floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def __lowercase ( self ): """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=lowerCamelCase__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=lowerCamelCase__ , ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) : int =config_and_inputs __UpperCamelCase : Optional[Any] ={ 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class __A ( a , a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : Union[str, Any] =(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () UpperCamelCase__ : str =(TFXGLMForCausalLM,) if is_tf_available() else () UpperCamelCase__ : Optional[Any] =( {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {} ) UpperCamelCase__ : Tuple =False UpperCamelCase__ : Tuple =False UpperCamelCase__ : Optional[Any] =False def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =TFXGLMModelTester(self ) __UpperCamelCase : Dict =ConfigTester(self , config_class=lowerCamelCase__ , n_embd=37 ) def __lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() @slow def __lowercase ( self ): """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Optional[Any] =TFXGLMModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' ) def __lowercase ( self ): """simple docstring""" super().test_resize_token_embeddings() @require_tf class __A ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self , lowerCamelCase__=True ): """simple docstring""" __UpperCamelCase : int =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : List[str] =tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __UpperCamelCase : str =[2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581] # fmt: on __UpperCamelCase : Optional[Any] =model.generate(lowerCamelCase__ , do_sample=lowerCamelCase__ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Union[str, Any] =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) tf.random.set_seed(0 ) __UpperCamelCase : str =tokenizer('Today is a nice day and' , return_tensors='tf' ) __UpperCamelCase : Union[str, Any] =tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0' ): __UpperCamelCase : Any =model.generate(lowerCamelCase__ , do_sample=lowerCamelCase__ , seed=[7, 0] ) __UpperCamelCase : Tuple =tokenizer.decode(output_ids[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : List[Any] =( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Optional[Any] =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Optional[Any] ='left' # use different length sentences to test batching __UpperCamelCase : Optional[int] =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __UpperCamelCase : List[Any] =tokenizer(lowerCamelCase__ , return_tensors='tf' , padding=lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =inputs['input_ids'] __UpperCamelCase : Dict =model.generate(input_ids=lowerCamelCase__ , attention_mask=inputs['attention_mask'] , max_new_tokens=12 ) __UpperCamelCase : List[Any] =tokenizer(sentences[0] , return_tensors='tf' ).input_ids __UpperCamelCase : Dict =model.generate(input_ids=lowerCamelCase__ , max_new_tokens=12 ) __UpperCamelCase : Any =tokenizer(sentences[1] , return_tensors='tf' ).input_ids __UpperCamelCase : Optional[Any] =model.generate(input_ids=lowerCamelCase__ , max_new_tokens=12 ) __UpperCamelCase : Optional[int] =tokenizer.batch_decode(lowerCamelCase__ , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : int =tokenizer.decode(output_padded[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : Any =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , [non_padded_sentence, padded_sentence] )
71
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() A : Tuple = logging.get_logger(__name__) A : Tuple = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] A : Optional[Any] = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = torch.load(_UpperCamelCase , map_location="cpu" ) return sd def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=rename_keys_prefix ): '''simple docstring''' __lowerCAmelCase = OrderedDict() __lowerCAmelCase = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __lowerCAmelCase = key for name_pair in rename_keys_prefix: __lowerCAmelCase = new_key.replace(name_pair[0] , name_pair[1] ) __lowerCAmelCase = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __lowerCAmelCase = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}." # Get Config if "pre" in checkpoint_path: __lowerCAmelCase = "pretraining" if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 1024} else: raise NotImplementedError(f"No implementation found for `{checkpoint_path}`." ) else: if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} __lowerCAmelCase = "multichoice" elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} __lowerCAmelCase = "vqa_advanced" elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048, "num_labels": 3129} __lowerCAmelCase = "vqa" elif "nlvr" in checkpoint_path: __lowerCAmelCase = { "visual_embedding_dim": 1024, "num_labels": 2, } __lowerCAmelCase = "nlvr" __lowerCAmelCase = VisualBertConfig(**_UpperCamelCase ) # Load State Dict __lowerCAmelCase = load_state_dict(_UpperCamelCase ) __lowerCAmelCase = get_new_dict(_UpperCamelCase , _UpperCamelCase ) if model_type == "pretraining": __lowerCAmelCase = VisualBertForPreTraining(_UpperCamelCase ) elif model_type == "vqa": __lowerCAmelCase = VisualBertForQuestionAnswering(_UpperCamelCase ) elif model_type == "nlvr": __lowerCAmelCase = VisualBertForVisualReasoning(_UpperCamelCase ) elif model_type == "multichoice": __lowerCAmelCase = VisualBertForMultipleChoice(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Save Checkpoints Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") A : Optional[int] = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
57
0
"""simple docstring""" from collections import defaultdict def snake_case_ ( A_ : int ): '''simple docstring''' _lowerCamelCase : Dict = 1 _lowerCamelCase : List[Any] = True for v in tree[start]: if v not in visited: ret += dfs(A_ ) if ret % 2 == 0: cuts.append(A_ ) return ret def snake_case_ ( ): '''simple docstring''' dfs(1 ) if __name__ == "__main__": lowerCAmelCase__ , lowerCAmelCase__ = 10, 9 lowerCAmelCase__ = defaultdict(list) lowerCAmelCase__ = {} lowerCAmelCase__ = [] lowerCAmelCase__ = 0 lowerCAmelCase__ = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
72
"""simple docstring""" class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [ [], [], [], ] def snake_case ( self , __a , __a ): try: if len(self.queues[priority] ) >= 1_00: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(__a ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def snake_case ( self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues ) ) class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): if len(self.queue ) == 1_00: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(__a ) def snake_case ( self ): if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(__a ) return data def __str__( self ): return str(self.queue ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
57
0
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) a ={ """sample_size""": 32, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": 1000, """block_out_channels""": [32, 64], """attention_head_dim""": 8, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } a ={ """sample_size""": 64, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 3, """num_class_embeds""": 1000, """block_out_channels""": [192, 192 * 2, 192 * 3, 192 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """scale_shift""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } a ={ """sample_size""": 256, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_class_embeds""": None, """block_out_channels""": [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], """attention_head_dim""": 64, """down_block_types""": [ """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """ResnetDownsampleBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", """AttnDownBlock2D""", ], """up_block_types""": [ """AttnUpBlock2D""", """AttnUpBlock2D""", """AttnUpBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", """ResnetUpsampleBlock2D""", ], """resnet_time_scale_shift""": """default""", """upsample_type""": """resnet""", """downsample_type""": """resnet""", } a ={ """num_train_timesteps""": 40, """sigma_min""": 0.0_02, """sigma_max""": 80.0, } a ={ """num_train_timesteps""": 201, """sigma_min""": 0.0_02, """sigma_max""": 80.0, } a ={ """num_train_timesteps""": 151, """sigma_min""": 0.0_02, """sigma_max""": 80.0, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[int]: if isinstance(lowerCamelCase__ , lowerCamelCase__ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError('boolean value expected' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ) -> Tuple: __lowerCamelCase : List[str] = checkpoint[F"{old_prefix}.in_layers.0.weight"] __lowerCamelCase : Any = checkpoint[F"{old_prefix}.in_layers.0.bias"] __lowerCamelCase : Optional[int] = checkpoint[F"{old_prefix}.in_layers.2.weight"] __lowerCamelCase : Tuple = checkpoint[F"{old_prefix}.in_layers.2.bias"] __lowerCamelCase : Optional[Any] = checkpoint[F"{old_prefix}.emb_layers.1.weight"] __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.emb_layers.1.bias"] __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.out_layers.0.weight"] __lowerCamelCase : str = checkpoint[F"{old_prefix}.out_layers.0.bias"] __lowerCamelCase : Optional[Any] = checkpoint[F"{old_prefix}.out_layers.3.weight"] __lowerCamelCase : Optional[int] = checkpoint[F"{old_prefix}.out_layers.3.bias"] if has_skip: __lowerCamelCase : str = checkpoint[F"{old_prefix}.skip_connection.weight"] __lowerCamelCase : Optional[int] = checkpoint[F"{old_prefix}.skip_connection.bias"] return new_checkpoint def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> Tuple: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[str] = checkpoint[F"{old_prefix}.qkv.weight"].chunk(3 , dim=0 ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.qkv.bias"].chunk(3 , dim=0 ) __lowerCamelCase : int = checkpoint[F"{old_prefix}.norm.weight"] __lowerCamelCase : List[Any] = checkpoint[F"{old_prefix}.norm.bias"] __lowerCamelCase : Dict = weight_q.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : int = bias_q.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Optional[Any] = weight_k.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Any = bias_k.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Tuple = weight_v.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Any = bias_v.squeeze(-1 ).squeeze(-1 ) __lowerCamelCase : Union[str, Any] = ( checkpoint[F"{old_prefix}.proj_out.weight"].squeeze(-1 ).squeeze(-1 ) ) __lowerCamelCase : Union[str, Any] = checkpoint[F"{old_prefix}.proj_out.bias"].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[Any]: __lowerCamelCase : int = torch.load(lowerCamelCase__ , map_location='cpu' ) __lowerCamelCase : Optional[int] = {} __lowerCamelCase : Dict = checkpoint['time_embed.0.weight'] __lowerCamelCase : Optional[Any] = checkpoint['time_embed.0.bias'] __lowerCamelCase : Dict = checkpoint['time_embed.2.weight'] __lowerCamelCase : int = checkpoint['time_embed.2.bias'] if unet_config["num_class_embeds"] is not None: __lowerCamelCase : Optional[Any] = checkpoint['label_emb.weight'] __lowerCamelCase : str = checkpoint['input_blocks.0.0.weight'] __lowerCamelCase : List[Any] = checkpoint['input_blocks.0.0.bias'] __lowerCamelCase : Tuple = unet_config['down_block_types'] __lowerCamelCase : Optional[Any] = unet_config['layers_per_block'] __lowerCamelCase : Any = unet_config['attention_head_dim'] __lowerCamelCase : Any = unet_config['block_out_channels'] __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : Tuple = channels_list[0] for i, layer_type in enumerate(lowerCamelCase__ ): __lowerCamelCase : str = channels_list[i] __lowerCamelCase : List[str] = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(lowerCamelCase__ ): __lowerCamelCase : List[Any] = F"down_blocks.{i}.resnets.{j}" __lowerCamelCase : int = F"input_blocks.{current_layer}.0" __lowerCamelCase : int = True if j == 0 and downsample_block_has_skip else False __lowerCamelCase : List[Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = F"down_blocks.{i}.resnets.{j}" __lowerCamelCase : Optional[int] = F"input_blocks.{current_layer}.0" __lowerCamelCase : Optional[Any] = True if j == 0 and downsample_block_has_skip else False __lowerCamelCase : List[Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) __lowerCamelCase : Any = F"down_blocks.{i}.attentions.{j}" __lowerCamelCase : Union[str, Any] = F"input_blocks.{current_layer}.1" __lowerCamelCase : List[Any] = convert_attention( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) current_layer += 1 if i != len(lowerCamelCase__ ) - 1: __lowerCamelCase : Tuple = F"down_blocks.{i}.downsamplers.0" __lowerCamelCase : Any = F"input_blocks.{current_layer}.0" __lowerCamelCase : Any = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) current_layer += 1 __lowerCamelCase : Union[str, Any] = current_channels # hardcoded the mid-block for now __lowerCamelCase : Optional[Any] = 'mid_block.resnets.0' __lowerCamelCase : Any = 'middle_block.0' __lowerCamelCase : Any = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : str = 'mid_block.attentions.0' __lowerCamelCase : Union[str, Any] = 'middle_block.1' __lowerCamelCase : str = convert_attention(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 'mid_block.resnets.1' __lowerCamelCase : Optional[int] = 'middle_block.2' __lowerCamelCase : Union[str, Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : str = 0 __lowerCamelCase : Union[str, Any] = unet_config['up_block_types'] for i, layer_type in enumerate(lowerCamelCase__ ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): __lowerCamelCase : Optional[int] = F"up_blocks.{i}.resnets.{j}" __lowerCamelCase : str = F"output_blocks.{current_layer}.0" __lowerCamelCase : Union[str, Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) current_layer += 1 if i != len(lowerCamelCase__ ) - 1: __lowerCamelCase : List[str] = F"up_blocks.{i}.upsamplers.0" __lowerCamelCase : str = F"output_blocks.{current_layer-1}.1" __lowerCamelCase : Dict = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): __lowerCamelCase : Dict = F"up_blocks.{i}.resnets.{j}" __lowerCamelCase : int = F"output_blocks.{current_layer}.0" __lowerCamelCase : Optional[int] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ ) __lowerCamelCase : List[str] = F"up_blocks.{i}.attentions.{j}" __lowerCamelCase : Dict = F"output_blocks.{current_layer}.1" __lowerCamelCase : Dict = convert_attention( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) current_layer += 1 if i != len(lowerCamelCase__ ) - 1: __lowerCamelCase : int = F"up_blocks.{i}.upsamplers.0" __lowerCamelCase : str = F"output_blocks.{current_layer-1}.2" __lowerCamelCase : Optional[int] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = checkpoint['out.0.weight'] __lowerCamelCase : Dict = checkpoint['out.0.bias'] __lowerCamelCase : Optional[int] = checkpoint['out.2.weight'] __lowerCamelCase : List[str] = checkpoint['out.2.bias'] return new_checkpoint if __name__ == "__main__": a =argparse.ArgumentParser() parser.add_argument("""--unet_path""", default=None, type=str, required=True, help="""Path to the unet.pt to convert.""") parser.add_argument( """--dump_path""", default=None, type=str, required=True, help="""Path to output the converted UNet model.""" ) parser.add_argument("""--class_cond""", default=True, type=str, help="""Whether the model is class-conditional.""") a =parser.parse_args() a =strabool(args.class_cond) a =os.path.basename(args.unet_path) print(F"""Checkpoint: {ckpt_name}""") # Get U-Net config if "imagenet64" in ckpt_name: a =IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): a =LSUN_256_UNET_CONFIG elif "test" in ckpt_name: a =TEST_UNET_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") if not args.class_cond: a =None a =con_pt_to_diffuser(args.unet_path, unet_config) a =UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: a =CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: a =CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): a =CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F"""Checkpoint type {ckpt_name} is not currently supported.""") a =CMStochasticIterativeScheduler(**scheduler_config) a =ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
73
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' 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\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) __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()
57
0
"""simple docstring""" import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _lowercase = get_tests_dir('''fixtures/test_sentencepiece_bpe.model''') class lowerCAmelCase_ ( _lowercase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase: List[str] = BartphoTokenizer _lowerCamelCase: Tuple = False _lowerCamelCase: Optional[int] = True def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: super().setUp() A = ['▁This', '▁is', '▁a', '▁t', 'est'] A = dict(zip(A_ ,range(len(A_ ) ) ) ) A = {'unk_token': '<unk>'} A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['monolingual_vocab_file'] ) with open(self.monolingual_vocab_file ,'w' ,encoding='utf-8' ) as fp: for token in vocab_tokens: fp.write(F'{token} {vocab_tokens[token]}\n' ) A = BartphoTokenizer(A_ ,self.monolingual_vocab_file ,**self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self : Any ,**A_ : List[str] ) -> List[Any]: kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname ,**A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Any ) -> str: A = 'This is a là test' A = 'This is a<unk><unk> test' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: A = BartphoTokenizer(A_ ,self.monolingual_vocab_file ,**self.special_tokens_map ) A = 'This is a là test' A = '▁This ▁is ▁a ▁l à ▁t est'.split() A = tokenizer.tokenize(A_ ) self.assertListEqual(A_ ,A_ ) A = tokens + [tokenizer.unk_token] A = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) ,A_ )
74
"""simple docstring""" def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = 1 while len(_UpperCamelCase ) < 1e6: constant.append(str(_UpperCamelCase ) ) i += 1 __lowerCAmelCase = "".join(_UpperCamelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
57
0
'''simple docstring''' from __future__ import annotations import requests a_ : List[Any] = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def a_ ( __snake_case : str , __snake_case : int = 1 , __snake_case : str = "new" , __snake_case : list | None = None ) -> dict: """simple docstring""" lowerCamelCase_ =wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(__snake_case ) - valid_terms ) ): lowerCamelCase_ =F'''Invalid search term: {invalid_search_terms}''' raise ValueError(__snake_case ) lowerCamelCase_ =requests.get( F'''https://reddit.com/r/{subreddit}/{age}.json?limit={limit}''' , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError lowerCamelCase_ =response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(__snake_case )} lowerCamelCase_ ={} for id_ in range(__snake_case ): lowerCamelCase_ ={ item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("""learnpython""", wanted_data=["""title""", """url""", """selftext"""]))
75
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs A : Union[str, Any] = imread(R"digital_image_processing/image_data/lena_small.jpg") A : Optional[Any] = cvtColor(img, COLOR_BGR2GRAY) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = cn.convert_to_negative(_UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def _lowerCamelCase ( ): '''simple docstring''' with Image.open("digital_image_processing/image_data/lena_small.jpg" ) as img: # Work around assertion for response assert str(cc.change_contrast(_UpperCamelCase , 110 ) ).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = imread("digital_image_processing/image_data/lena_small.jpg" , 0 ) # assert ambiguous array for all == True assert canny_img.all() __lowerCAmelCase = canny.canny(_UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def _lowerCamelCase ( ): '''simple docstring''' assert gg.gaussian_filter(_UpperCamelCase , 5 , sigma=0.9 ).all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __lowerCAmelCase = conv.img_convolve(_UpperCamelCase , _UpperCamelCase ).astype(_UpperCamelCase ) assert res.any() def _lowerCamelCase ( ): '''simple docstring''' assert med.median_filter(_UpperCamelCase , 3 ).any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase = sob.sobel_filter(_UpperCamelCase ) assert grad.any() and theta.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = sp.make_sepia(_UpperCamelCase , 20 ) assert sepia.all() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' __lowerCAmelCase = bs.Burkes(imread(_UpperCamelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' __lowerCAmelCase = rs.NearestNeighbour(imread(_UpperCamelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. __lowerCAmelCase = imread(_UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = image[x_coordinate][y_coordinate] __lowerCAmelCase = lbp.get_neighbors_pixel( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __lowerCAmelCase = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __lowerCAmelCase = lbp.local_binary_value(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert lbp_image.any()
57
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='speech_to_text' lowerCamelCase__ =['past_key_values'] lowerCamelCase__ ={'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : Optional[int] , a : Optional[int]=1_0000 , a : Any=12 , a : List[Any]=2048 , a : Any=4 , a : str=6 , a : List[str]=2048 , a : str=4 , a : Tuple=0.0 , a : Dict=0.0 , a : Union[str, Any]=True , a : Any=True , a : Tuple="relu" , a : int=256 , a : Dict=0.1 , a : int=0.0 , a : List[str]=0.0 , a : Dict=0.02 , a : Tuple=2 , a : Tuple=True , a : Optional[Any]=1 , a : int=0 , a : Tuple=2 , a : str=6000 , a : List[Any]=1024 , a : int=2 , a : Optional[Any]=(5, 5) , a : Dict=1024 , a : int=80 , a : Optional[int]=1 , **a : str , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : str = d_model SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_ffn_dim SCREAMING_SNAKE_CASE : Any = encoder_layers SCREAMING_SNAKE_CASE : int = encoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = decoder_ffn_dim SCREAMING_SNAKE_CASE : Any = decoder_layers SCREAMING_SNAKE_CASE : Optional[int] = decoder_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = dropout SCREAMING_SNAKE_CASE : str = attention_dropout SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout SCREAMING_SNAKE_CASE : str = activation_function SCREAMING_SNAKE_CASE : Any = init_std SCREAMING_SNAKE_CASE : Any = encoder_layerdrop SCREAMING_SNAKE_CASE : int = decoder_layerdrop SCREAMING_SNAKE_CASE : Tuple = use_cache SCREAMING_SNAKE_CASE : Optional[int] = encoder_layers SCREAMING_SNAKE_CASE : str = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE : Union[str, Any] = max_source_positions SCREAMING_SNAKE_CASE : str = max_target_positions SCREAMING_SNAKE_CASE : Optional[int] = num_conv_layers SCREAMING_SNAKE_CASE : Union[str, Any] = list(a ) SCREAMING_SNAKE_CASE : Optional[int] = conv_channels SCREAMING_SNAKE_CASE : Dict = input_feat_per_channel SCREAMING_SNAKE_CASE : Optional[Any] = input_channels if len(self.conv_kernel_sizes ) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` " F"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, " F"`config.num_conv_layers = {self.num_conv_layers}`." ) super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , is_encoder_decoder=a , decoder_start_token_id=a , **a , )
76
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : Optional[int] = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltCLIPTextConfig", "AltCLIPVisionConfig", ], "processing_altclip": ["AltCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = [ "ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "AltCLIPPreTrainedModel", "AltCLIPModel", "AltCLIPTextModel", "AltCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys A : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
"""simple docstring""" import logging import os from .state import PartialState class UpperCAmelCase_ ( logging.LoggerAdapter): @staticmethod def _UpperCAmelCase ( a ) -> Dict: lowercase__ : Any = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _UpperCAmelCase ( self , a , a , *a , **a ) -> Union[str, Any]: if PartialState._shared_state == {}: raise RuntimeError( 'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.' ) lowercase__ : str = kwargs.pop('main_process_only' , a ) lowercase__ : Optional[int] = kwargs.pop('in_order' , a ) if self.isEnabledFor(a ): if self._should_log(a ): lowercase__ , lowercase__ : int = self.process(a , a ) self.logger.log(a , a , *a , **a ) elif in_order: lowercase__ : Dict = PartialState() for i in range(state.num_processes ): if i == state.process_index: lowercase__ , lowercase__ : Optional[Any] = self.process(a , a ) self.logger.log(a , a , *a , **a ) state.wait_for_everyone() def a_ ( _lowerCAmelCase : str , _lowerCAmelCase : str = None ): '''simple docstring''' if log_level is None: lowercase__ : Optional[Any] = os.environ.get('ACCELERATE_LOG_LEVEL' , _lowerCAmelCase ) lowercase__ : List[Any] = logging.getLogger(_lowerCAmelCase ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(_lowerCAmelCase , {} )
77
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A : Dict = logging.getLogger(__name__) @dataclass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[float] =field( default=0.0 ,metadata={"""help""": """The label smoothing epsilon to apply (if not zero)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """Whether to SortishSamler or not."""} ) __UpperCAmelCase : bool =field( default=lowerCAmelCase__ ,metadata={"""help""": """Whether to use generate to calculate generative metrics (ROUGE, BLEU)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """whether to use adafactor"""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Encoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Decoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field(default=lowerCAmelCase__ ,metadata={"""help""": """Dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Attention dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[str] =field( default="""linear""" ,metadata={"""help""": F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} ,)
57
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available snake_case_ = { """configuration_biogpt""": ["""BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BioGptConfig"""], """tokenization_biogpt""": ["""BioGptTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ """BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BioGptForCausalLM""", """BioGptForTokenClassification""", """BioGptForSequenceClassification""", """BioGptModel""", """BioGptPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
78
"""simple docstring""" import argparse import os import re import packaging.version A : Any = "examples/" A : Optional[Any] = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } A : Optional[int] = { "init": "src/transformers/__init__.py", "setup": "setup.py", } A : List[Any] = "README.md" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , _UpperCamelCase ) __lowerCAmelCase = re_pattern.sub(_UpperCamelCase , _UpperCamelCase ) with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for folder, directories, fnames in os.walk(_UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase , pattern="examples" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if not patch: update_version_in_examples(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(_UpperCamelCase ).groups()[0] return packaging.version.parse(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase=False ): '''simple docstring''' __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __lowerCAmelCase = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(f"Which version are you releasing? [{default_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = default_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase , patch=_UpperCamelCase ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = get_version() __lowerCAmelCase = f"{current_version.major}.{current_version.minor + 1}.0.dev0" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(f"Which version are we developing now? [{dev_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = dev_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") A : Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
57
0
'''simple docstring''' import math def __lowercase ( __lowercase = 100 ) -> int: '''simple docstring''' _A = sum(i * i for i in range(1 , n + 1 ) ) _A = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
79
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A : Tuple = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Dict = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : str = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys A : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(a ) UpperCamelCase__ = resnets UpperCamelCase__ = attentions if self.add_downsample: UpperCamelCase__ = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a , a=True ): UpperCamelCase__ = () for resnet, attn in zip(self.resnets , self.attentions ): UpperCamelCase__ = resnet(a , a , deterministic=a ) UpperCamelCase__ = attn(a , a , deterministic=a ) output_states += (hidden_states,) if self.add_downsample: UpperCamelCase__ = self.downsamplers_a(a ) output_states += (hidden_states,) return hidden_states, output_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = resnets if self.add_downsample: UpperCamelCase__ = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a=True ): UpperCamelCase__ = () for resnet in self.resnets: UpperCamelCase__ = resnet(a , a , deterministic=a ) output_states += (hidden_states,) if self.add_downsample: UpperCamelCase__ = self.downsamplers_a(a ) output_states += (hidden_states,) return hidden_states, output_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCamelCase__ = self.prev_output_channel if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(a ) UpperCamelCase__ = resnets UpperCamelCase__ = attentions if self.add_upsample: UpperCamelCase__ = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a , a , a=True ): for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states UpperCamelCase__ = res_hidden_states_tuple[-1] UpperCamelCase__ = res_hidden_states_tuple[:-1] UpperCamelCase__ = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCamelCase__ = resnet(a , a , deterministic=a ) UpperCamelCase__ = attn(a , a , deterministic=a ) if self.add_upsample: UpperCamelCase__ = self.upsamplers_a(a ) return hidden_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = True __UpperCAmelCase = jnp.floataa def __a ( self ): UpperCamelCase__ = [] for i in range(self.num_layers ): UpperCamelCase__ = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCamelCase__ = self.prev_output_channel if i == 0 else self.out_channels UpperCamelCase__ = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = resnets if self.add_upsample: UpperCamelCase__ = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , a , a , a , a=True ): for resnet in self.resnets: # pop res hidden states UpperCamelCase__ = res_hidden_states_tuple[-1] UpperCamelCase__ = res_hidden_states_tuple[:-1] UpperCamelCase__ = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCamelCase__ = resnet(a , a , deterministic=a ) if self.add_upsample: UpperCamelCase__ = self.upsamplers_a(a ) return hidden_states class lowercase_ ( nn.Module ): __UpperCAmelCase = 42 __UpperCAmelCase = 0.0 __UpperCAmelCase = 1 __UpperCAmelCase = 1 __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = jnp.floataa def __a ( self ): # there is always at least one resnet UpperCamelCase__ = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] UpperCamelCase__ = [] for _ in range(self.num_layers ): UpperCamelCase__ = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(a ) UpperCamelCase__ = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(a ) UpperCamelCase__ = resnets UpperCamelCase__ = attentions def __call__( self , a , a , a , a=True ): UpperCamelCase__ = self.resnets[0](a , a ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): UpperCamelCase__ = attn(a , a , deterministic=a ) UpperCamelCase__ = resnet(a , a , deterministic=a ) return hidden_states
80
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase = 6008_5147_5143 ): '''simple docstring''' try: __lowerCAmelCase = int(_UpperCamelCase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) __lowerCAmelCase = 2 __lowerCAmelCase = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 __lowerCAmelCase = i while n % i == 0: __lowerCAmelCase = n // i i += 1 return int(_UpperCamelCase ) if __name__ == "__main__": print(f'''{solution() = }''')
57
0
"""simple docstring""" import sys lowerCamelCase_ : Dict = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def _A ( lowercase = N ): """simple docstring""" a =-sys.maxsize - 1 for i in range(len(lowercase ) - 12 ): a =1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: a =product return largest_product if __name__ == "__main__": print(F'{solution() = }')
81
"""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 _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__( self , __a , __a=None , __a=True , __a=None , **__a ): __lowerCAmelCase = parent __lowerCAmelCase = config_class __lowerCAmelCase = has_text_modality __lowerCAmelCase = kwargs __lowerCAmelCase = common_properties def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = ( ["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(__a , __a ) , msg=f"`{prop}` does not exist" ) # Test that config has the common properties as setter for idx, name in enumerate(__a ): try: setattr(__a , __a , __a ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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(__a ): try: __lowerCAmelCase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(__a , __a ) , __a , msg=f"`{name} value {idx} expected, but was {getattr(__a , __a )}" ) 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 ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , __a ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , "config.json" ) config_first.to_json_file(__a ) __lowerCAmelCase = self.config_class.from_json_file(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict ) __lowerCAmelCase = "test" with tempfile.TemporaryDirectory() as tmpdirname: __lowerCAmelCase = os.path.join(__a , __a ) config_first.save_pretrained(__a ) __lowerCAmelCase = self.config_class.from_pretrained(__a , subfolder=__a ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def snake_case ( self ): __lowerCAmelCase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) __lowerCAmelCase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def snake_case ( self ): if self.config_class.is_composition: return __lowerCAmelCase = self.config_class() self.parent.assertIsNotNone(__a ) def snake_case ( self ): __lowerCAmelCase = copy.deepcopy(__a ) __lowerCAmelCase = self.config_class(**__a ) __lowerCAmelCase = [] 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(__a , __a ) != value: wrong_values.append((key, getattr(__a , __a ), value) ) if len(__a ) > 0: __lowerCAmelCase = "\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 ): 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()
57
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ = {"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = [ """FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FocalNetForImageClassification""", """FocalNetForMaskedImageModeling""", """FocalNetBackbone""", """FocalNetModel""", """FocalNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys A__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
82
"""simple docstring""" A : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
57
0
'''simple docstring''' from math import pi def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): return 2 * pi * radius * (angle / 3_6_0) if __name__ == "__main__": print(arc_length(90, 10))
83
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : str = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : str =["""input_ids""", """attention_mask"""] def __init__( self , __a="</s>" , __a="<unk>" , __a="<pad>" , __a=1_25 , __a=None , **__a , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __lowerCAmelCase = [f"<extra_id_{i}>" for i in range(__a )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __lowerCAmelCase = len(set(filter(lambda __a : bool("extra_id" in str(__a ) ) , __a ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the" " extra_ids tokens" ) __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else pad_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else eos_token __lowerCAmelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else unk_token super().__init__( eos_token=__a , unk_token=__a , pad_token=__a , extra_ids=__a , additional_special_tokens=__a , **__a , ) __lowerCAmelCase = extra_ids __lowerCAmelCase = 2**8 # utf is 8 bits # define special tokens dict __lowerCAmelCase = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __lowerCAmelCase = len(self.special_tokens_encoder ) __lowerCAmelCase = len(__a ) for i, token in enumerate(__a ): __lowerCAmelCase = self.vocab_size + i - n __lowerCAmelCase = {v: k for k, v in self.special_tokens_encoder.items()} @property def snake_case ( self ): return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def snake_case ( self , __a , __a = None , __a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__a )) + [1] return ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] def snake_case ( self , __a ): if len(__a ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated" " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def snake_case ( self , __a , __a = None ): __lowerCAmelCase = self._add_eos_if_not_present(__a ) if token_ids_a is None: return token_ids_a else: __lowerCAmelCase = self._add_eos_if_not_present(__a ) return token_ids_a + token_ids_a def snake_case ( self , __a ): __lowerCAmelCase = [chr(__a ) for i in text.encode("utf-8" )] return tokens def snake_case ( self , __a ): if token in self.special_tokens_encoder: __lowerCAmelCase = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __lowerCAmelCase = self.added_tokens_encoder[token] elif len(__a ) != 1: __lowerCAmelCase = self.unk_token_id else: __lowerCAmelCase = ord(__a ) + self._num_special_tokens return token_id def snake_case ( self , __a ): if index in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[index] else: __lowerCAmelCase = chr(index - self._num_special_tokens ) return token def snake_case ( self , __a ): __lowerCAmelCase = B"" for token in tokens: if token in self.special_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.added_tokens_decoder: __lowerCAmelCase = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.special_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) elif token in self.added_tokens_encoder: __lowerCAmelCase = token.encode("utf-8" ) else: __lowerCAmelCase = bytes([ord(__a )] ) bstring += tok_string __lowerCAmelCase = bstring.decode("utf-8" , errors="ignore" ) return string def snake_case ( self , __a , __a = None ): return ()
57
0
"""simple docstring""" def _snake_case ( lowercase__ : int , lowercase__ : int ) -> int: '''simple docstring''' return int((input_a, input_a).count(1 ) != 0 ) def _snake_case ( ) -> None: '''simple docstring''' assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
84
"""simple docstring""" import numpy # List of input, output pairs A : Any = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) A : str = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) A : Union[str, Any] = [2, 4, 1, 5] A : int = len(train_data) A : Dict = 0.009 def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase="train" ): '''simple docstring''' return calculate_hypothesis_value(_UpperCamelCase , _UpperCamelCase ) - output( _UpperCamelCase , _UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(len(_UpperCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=m ): '''simple docstring''' __lowerCAmelCase = 0 for i in range(_UpperCamelCase ): if index == -1: summation_value += _error(_UpperCamelCase ) else: summation_value += _error(_UpperCamelCase ) * train_data[i][0][index] return summation_value def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = summation_of_cost_derivative(_UpperCamelCase , _UpperCamelCase ) / m return cost_derivative_value def _lowerCamelCase ( ): '''simple docstring''' global parameter_vector # Tune these values to set a tolerance value for predicted output __lowerCAmelCase = 0.00_00_02 __lowerCAmelCase = 0 __lowerCAmelCase = 0 while True: j += 1 __lowerCAmelCase = [0, 0, 0, 0] for i in range(0 , len(_UpperCamelCase ) ): __lowerCAmelCase = get_cost_derivative(i - 1 ) __lowerCAmelCase = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( _UpperCamelCase , _UpperCamelCase , atol=_UpperCamelCase , rtol=_UpperCamelCase , ): break __lowerCAmelCase = temp_parameter_vector print(("Number of iterations:", j) ) def _lowerCamelCase ( ): '''simple docstring''' for i in range(len(_UpperCamelCase ) ): print(("Actual output value:", output(_UpperCamelCase , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(_UpperCamelCase , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
57
0
'''simple docstring''' from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) _SCREAMING_SNAKE_CASE : List[str] = 2_9979_2458 # Symbols _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = symbols("ct x y z") def UpperCamelCase_( snake_case : float ): '''simple docstring''' if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!" ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!" ) return velocity / c def UpperCamelCase_( snake_case : float ): '''simple docstring''' return 1 / sqrt(1 - beta(snake_case ) ** 2 ) def UpperCamelCase_( snake_case : float ): '''simple docstring''' return np.array( [ [gamma(snake_case ), -gamma(snake_case ) * beta(snake_case ), 0, 0], [-gamma(snake_case ) * beta(snake_case ), gamma(snake_case ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def UpperCamelCase_( snake_case : float , snake_case : np.ndarray | None = None ): '''simple docstring''' if event is None: snake_case_ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(snake_case ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: _SCREAMING_SNAKE_CASE : List[str] = transform(2997_9245) print("Example of four vector: ") print(F"ct' = {four_vector[0]}") print(F"x' = {four_vector[1]}") print(F"y' = {four_vector[2]}") print(F"z' = {four_vector[3]}") # Substitute symbols with numerical values _SCREAMING_SNAKE_CASE : List[Any] = {ct: c, x: 1, y: 1, z: 1} _SCREAMING_SNAKE_CASE : List[Any] = [four_vector[i].subs(sub_dict) for i in range(4)] print(F"\n{numerical_vector}")
85
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): __lowerCAmelCase = tempfile.mkdtemp() __lowerCAmelCase = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "的", "价", "格", "是", "15", "便", "alex", "##andra", ",", "。", "-", "t", "shirt", ] __lowerCAmelCase = 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] ) ) __lowerCAmelCase = { "do_resize": True, "size": {"height": 2_24, "width": 2_24}, "do_center_crop": True, "crop_size": {"height": 18, "width": 18}, "do_normalize": True, "image_mean": [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], "image_std": [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], "do_convert_rgb": True, } __lowerCAmelCase = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(__a , __a ) def snake_case ( self , **__a ): return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return BertTokenizerFast.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self , **__a ): return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **__a ) def snake_case ( self ): shutil.rmtree(self.tmpdirname ) def snake_case ( self ): __lowerCAmelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCAmelCase = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self ): __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__a ) __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __a ) self.assertIsInstance(processor_fast.tokenizer , __a ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __a ) self.assertIsInstance(processor_fast.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase = self.get_tokenizer(cls_token="(CLS)" , sep_token="(SEP)" ) __lowerCAmelCase = self.get_image_processor(do_normalize=__a ) __lowerCAmelCase = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="(CLS)" , sep_token="(SEP)" , do_normalize=__a ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = image_processor(__a , return_tensors="np" ) __lowerCAmelCase = processor(images=__a , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = processor(text=__a ) __lowerCAmelCase = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(__a ): processor() def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase = processor.batch_decode(__a ) __lowerCAmelCase = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def snake_case ( self ): __lowerCAmelCase = self.get_image_processor() __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = ChineseCLIPProcessor(tokenizer=__a , image_processor=__a ) __lowerCAmelCase = "Alexandra,T-shirt的价格是15便士。" __lowerCAmelCase = self.prepare_image_inputs() __lowerCAmelCase = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
57
0
"""simple docstring""" import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class A__ ( enum.Enum): A_ : List[Any] = 0 A_ : Dict = 1 A_ : Union[str, Any] = 2 @add_end_docstrings(_lowerCamelCase) class A__ ( _lowerCamelCase): A_ : str = '\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n ' def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. __lowerCAmelCase : Any = None if self.model.config.prefix is not None: __lowerCAmelCase : str = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. __lowerCAmelCase : Tuple = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = self._sanitize_parameters(prefix=_SCREAMING_SNAKE_CASE , **self._forward_params ) __lowerCAmelCase : List[str] = {**self._preprocess_params, **preprocess_params} __lowerCAmelCase : List[str] = {**self._forward_params, **forward_params} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): __lowerCAmelCase : Optional[int] = {} if prefix is not None: __lowerCAmelCase : Union[str, Any] = prefix if prefix: __lowerCAmelCase : Dict = self.tokenizer( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : List[Any] = prefix_inputs['input_ids'].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" ' [None, \'hole\']' ) __lowerCAmelCase : int = handle_long_generation preprocess_params.update(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = generate_kwargs __lowerCAmelCase : List[Any] = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_full_text`' ) if return_tensors is not None: raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : Optional[Any] = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('`return_text` is mutually exclusive with `return_tensors`' ) __lowerCAmelCase : List[Any] = ReturnType.TENSORS if return_type is not None: __lowerCAmelCase : Optional[Any] = return_type if clean_up_tokenization_spaces is not None: __lowerCAmelCase : Tuple = clean_up_tokenization_spaces if stop_sequence is not None: __lowerCAmelCase : Union[str, Any] = self.tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 1: warnings.warn( 'Stopping on a multiple token sequence is not yet supported on transformers. The first token of' ' the stop sequence will be used as the stop sequence string in the interim.' ) __lowerCAmelCase : Optional[Any] = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __lowerCamelCase ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'add_space_before_punct_symbol': True} ) return super()._parse_and_tokenize(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="" , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = self.tokenizer( prefix + prompt_text , padding=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) __lowerCAmelCase : Optional[Any] = prompt_text if handle_long_generation == "hole": __lowerCAmelCase : str = inputs['input_ids'].shape[-1] if "max_new_tokens" in generate_kwargs: __lowerCAmelCase : Union[str, Any] = generate_kwargs['max_new_tokens'] else: __lowerCAmelCase : Any = generate_kwargs.get('max_length' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('We cannot infer how many new tokens are expected' ) if cur_len + new_tokens > self.tokenizer.model_max_length: __lowerCAmelCase : Any = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( 'We cannot use `hole` to handle this generation the number of desired tokens exceeds the' ' models max length' ) __lowerCAmelCase : int = inputs['input_ids'][:, -keep_length:] if "attention_mask" in inputs: __lowerCAmelCase : List[Any] = inputs['attention_mask'][:, -keep_length:] return inputs def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = model_inputs['input_ids'] __lowerCAmelCase : List[Any] = model_inputs.get('attention_mask' , _SCREAMING_SNAKE_CASE ) # Allow empty prompts if input_ids.shape[1] == 0: __lowerCAmelCase : Dict = None __lowerCAmelCase : str = None __lowerCAmelCase : Tuple = 1 else: __lowerCAmelCase : Any = input_ids.shape[0] __lowerCAmelCase : Union[str, Any] = model_inputs.pop('prompt_text' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. __lowerCAmelCase : Optional[int] = generate_kwargs.pop('prefix_length' , 0 ) if prefix_length > 0: __lowerCAmelCase : Any = 'max_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].max_new_tokens is not None ) if not has_max_new_tokens: __lowerCAmelCase : List[str] = generate_kwargs.get('max_length' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length __lowerCAmelCase : Dict = 'min_new_tokens' in generate_kwargs or ( 'generation_config' in generate_kwargs and generate_kwargs['generation_config'].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL __lowerCAmelCase : Optional[int] = self.model.generate(input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = generated_sequence.shape[0] if self.framework == "pt": __lowerCAmelCase : Dict = generated_sequence.reshape(_SCREAMING_SNAKE_CASE , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": __lowerCAmelCase : Any = tf.reshape(_SCREAMING_SNAKE_CASE , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=ReturnType.FULL_TEXT , _SCREAMING_SNAKE_CASE=True ): __lowerCAmelCase : Any = model_outputs['generated_sequence'][0] __lowerCAmelCase : Tuple = model_outputs['input_ids'] __lowerCAmelCase : Any = model_outputs['prompt_text'] __lowerCAmelCase : int = generated_sequence.numpy().tolist() __lowerCAmelCase : Union[str, Any] = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: __lowerCAmelCase : int = {'generated_token_ids': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text __lowerCAmelCase : Any = self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: __lowerCAmelCase : Optional[Any] = 0 else: __lowerCAmelCase : Any = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE , ) ) if return_type == ReturnType.FULL_TEXT: __lowerCAmelCase : Union[str, Any] = prompt_text + text[prompt_length:] else: __lowerCAmelCase : int = text[prompt_length:] __lowerCAmelCase : Dict = {'generated_text': all_text} records.append(_SCREAMING_SNAKE_CASE ) return records
86
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( _UpperCamelCase = 4 ): '''simple docstring''' __lowerCAmelCase = abs(_UpperCamelCase ) or 4 return [[1 + x + y * row_size for x in range(_UpperCamelCase )] for y in range(_UpperCamelCase )] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_row(reverse_column(_UpperCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' return reverse_column(transpose(_UpperCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [list(_UpperCamelCase ) for x in zip(*_UpperCamelCase )] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = matrix[::-1] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [x[::-1] for x in matrix] return matrix def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for i in matrix: print(*_UpperCamelCase ) if __name__ == "__main__": A : Dict = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_aa(matrix)) A : List[str] = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_aaa(matrix)) A : str = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_aaa(matrix))
57
0
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html UpperCamelCase = '''platform''' import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def lowercase_ ( _lowerCamelCase : int , _lowerCamelCase : str , _lowerCamelCase : str=None , _lowerCamelCase : int=None , _lowerCamelCase : str=None , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : str=None , _lowerCamelCase : str=None , ): if attention_mask is None: lowercase__ : Dict = np.where(input_ids != config.pad_token_id , 1 , 0) if decoder_attention_mask is None: lowercase__ : Optional[Any] = np.where(decoder_input_ids != config.pad_token_id , 1 , 0) if head_mask is None: lowercase__ : str = np.ones((config.encoder_layers, config.encoder_attention_heads)) if decoder_head_mask is None: lowercase__ : Dict = np.ones((config.decoder_layers, config.decoder_attention_heads)) if cross_attn_head_mask is None: lowercase__ : int = np.ones((config.decoder_layers, config.decoder_attention_heads)) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class snake_case_ : def __init__( self : Dict , lowercase_ : Any , lowercase_ : List[str]=13 , lowercase_ : List[Any]=7 , lowercase_ : int=True , lowercase_ : Any=False , lowercase_ : int=99 , lowercase_ : Tuple=16 , lowercase_ : Optional[Any]=2 , lowercase_ : Union[str, Any]=4 , lowercase_ : Dict=4 , lowercase_ : Optional[Any]="gelu" , lowercase_ : Optional[int]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : Optional[Any]=32 , lowercase_ : Tuple=2 , lowercase_ : Any=1 , lowercase_ : List[str]=0 , lowercase_ : Union[str, Any]=0.02 , ) -> Dict: lowercase__ : Optional[int] = parent lowercase__ : str = batch_size lowercase__ : str = seq_length lowercase__ : Tuple = is_training lowercase__ : Optional[Any] = use_labels lowercase__ : List[Any] = vocab_size lowercase__ : str = hidden_size lowercase__ : Dict = num_hidden_layers lowercase__ : Any = num_attention_heads lowercase__ : Dict = intermediate_size lowercase__ : Tuple = hidden_act lowercase__ : List[str] = hidden_dropout_prob lowercase__ : Union[str, Any] = attention_probs_dropout_prob lowercase__ : List[Any] = max_position_embeddings lowercase__ : Optional[int] = eos_token_id lowercase__ : List[Any] = pad_token_id lowercase__ : Union[str, Any] = bos_token_id lowercase__ : Optional[int] = initializer_range def __UpperCamelCase ( self : Optional[Any] ) -> Tuple: lowercase__ : Any = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) lowercase__ : Tuple = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) lowercase__ : Tuple = shift_tokens_right(lowercase_ , 1 , 2 ) lowercase__ : Union[str, Any] = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowercase_ , ) lowercase__ : List[Any] = prepare_blenderbot_inputs_dict(lowercase_ , lowercase_ , lowercase_ ) return config, inputs_dict def __UpperCamelCase ( self : Tuple ) -> int: lowercase__ , lowercase__ : List[Any] = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCamelCase ( self : Any , lowercase_ : List[Any] , lowercase_ : Any , lowercase_ : List[Any] ) -> List[Any]: lowercase__ : Union[str, Any] = 20 lowercase__ : List[Any] = model_class_name(lowercase_ ) lowercase__ : Optional[int] = model.encode(inputs_dict["input_ids"] ) lowercase__ , lowercase__ : Optional[int] = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) lowercase__ : Optional[int] = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) lowercase__ : Tuple = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) lowercase__ : List[str] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ : int = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) lowercase__ : str = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) lowercase__ : Dict = model.decode( decoder_input_ids[:, -1:] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase_ , ) lowercase__ : Union[str, Any] = model.decode(lowercase_ , lowercase_ ) lowercase__ : Tuple = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F'''Max diff is {diff}''' ) def __UpperCamelCase ( self : Any , lowercase_ : Union[str, Any] , lowercase_ : Dict , lowercase_ : Any ) -> Union[str, Any]: lowercase__ : Optional[Any] = 20 lowercase__ : List[str] = model_class_name(lowercase_ ) lowercase__ : Any = model.encode(inputs_dict["input_ids"] ) lowercase__ , lowercase__ : List[str] = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) lowercase__ : Tuple = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) lowercase__ : List[str] = model.init_cache(decoder_input_ids.shape[0] , lowercase_ , lowercase_ ) lowercase__ : Tuple = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ : str = model.decode( decoder_input_ids[:, :-1] , lowercase_ , decoder_attention_mask=lowercase_ , past_key_values=lowercase_ , decoder_position_ids=lowercase_ , ) lowercase__ : Union[str, Any] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) lowercase__ : int = model.decode( decoder_input_ids[:, -1:] , lowercase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase_ , decoder_position_ids=lowercase_ , ) lowercase__ : int = model.decode(lowercase_ , lowercase_ , decoder_attention_mask=lowercase_ ) lowercase__ : Dict = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F'''Max diff is {diff}''' ) @require_flax class snake_case_ ( unittest.TestCase ): __A : Dict = 99 def __UpperCamelCase ( self : Any ) -> Tuple: lowercase__ : Tuple = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) lowercase__ : Tuple = input_ids.shape[0] lowercase__ : Union[str, Any] = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def __UpperCamelCase ( self : str ) -> Tuple: lowercase__ , lowercase__ , lowercase__ : Optional[int] = self._get_config_and_data() lowercase__ : Tuple = FlaxBlenderbotSmallForConditionalGeneration(lowercase_ ) lowercase__ : List[str] = lm_model(input_ids=lowercase_ ) lowercase__ : int = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["logits"].shape , lowercase_ ) def __UpperCamelCase ( self : Optional[Any] ) -> str: lowercase__ : List[Any] = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) lowercase__ : Dict = FlaxBlenderbotSmallForConditionalGeneration(lowercase_ ) lowercase__ : Optional[int] = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) lowercase__ : Union[str, Any] = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) lowercase__ : Union[str, Any] = lm_model(input_ids=lowercase_ , decoder_input_ids=lowercase_ ) lowercase__ : Optional[int] = (*summary.shape, config.vocab_size) self.assertEqual(outputs["logits"].shape , lowercase_ ) def __UpperCamelCase ( self : List[Any] ) -> str: lowercase__ : List[Any] = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) lowercase__ : int = shift_tokens_right(lowercase_ , 1 , 2 ) lowercase__ : Optional[int] = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() lowercase__ : Any = np.equal(lowercase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowercase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class snake_case_ ( __A ,unittest.TestCase ,__A ): __A : List[str] = True __A : List[str] = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) __A : str = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def __UpperCamelCase ( self : Any ) -> List[str]: lowercase__ : Dict = FlaxBlenderbotSmallModelTester(self ) def __UpperCamelCase ( self : str ) -> List[str]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase_ , lowercase_ , lowercase_ ) def __UpperCamelCase ( self : Any ) -> List[str]: lowercase__ , lowercase__ : Dict = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase_ , lowercase_ , lowercase_ ) def __UpperCamelCase ( self : Tuple ) -> List[str]: lowercase__ , lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ : Optional[int] = self._prepare_for_class(lowercase_ , lowercase_ ) lowercase__ : Union[str, Any] = model_class(lowercase_ ) @jax.jit def encode_jitted(lowercase_ : Any , lowercase_ : List[Any]=None , **lowercase_ : Dict ): return model.encode(input_ids=lowercase_ , attention_mask=lowercase_ ) with self.subTest("JIT Enabled" ): lowercase__ : List[str] = encode_jitted(**lowercase_ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowercase__ : Any = encode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCamelCase ( self : Union[str, Any] ) -> Optional[int]: lowercase__ , lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ : int = model_class(lowercase_ ) lowercase__ : List[str] = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) lowercase__ : int = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int] ): return model.decode( decoder_input_ids=lowercase_ , decoder_attention_mask=lowercase_ , encoder_outputs=lowercase_ , ) with self.subTest("JIT Enabled" ): lowercase__ : Any = decode_jitted(**lowercase_ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowercase__ : Tuple = decode_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __UpperCamelCase ( self : Dict ) -> int: for model_class_name in self.all_model_classes: lowercase__ : List[Any] = model_class_name.from_pretrained("facebook/blenderbot_small-90M" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids lowercase__ : Optional[Any] = np.ones((1, 1) ) * model.config.eos_token_id lowercase__ : str = model(lowercase_ ) self.assertIsNotNone(lowercase_ )
87
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCAmelCase : Union[str, Any] =TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def snake_case ( self , __a , __a , __a ): __lowerCAmelCase = TextaTextGenerationPipeline(model=__a , tokenizer=__a ) return generator, ["Something to write", "Something else"] def snake_case ( self , __a , __a ): __lowerCAmelCase = generator("Something there" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["generated_text"].startswith("Something there" ) ) __lowerCAmelCase = generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) __lowerCAmelCase = generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) with self.assertRaises(__a ): generator(4 ) @require_torch def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="pt" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] ) __lowerCAmelCase = 3 __lowerCAmelCase = generator( "Something there" , num_return_sequences=__a , num_beams=__a , ) __lowerCAmelCase = [ {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": ""}, ] self.assertEqual(__a , __a ) __lowerCAmelCase = generator("This is a test" , do_sample=__a , num_return_sequences=2 , return_tensors=__a ) self.assertEqual( __a , [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ] , ) __lowerCAmelCase = generator.model.config.eos_token_id __lowerCAmelCase = "<pad>" __lowerCAmelCase = generator( ["This is a test", "This is a second test"] , do_sample=__a , num_return_sequences=2 , batch_size=2 , return_tensors=__a , ) self.assertEqual( __a , [ [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], ] , ) @require_tf def snake_case ( self ): __lowerCAmelCase = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="tf" ) # do_sample=False necessary for reproducibility __lowerCAmelCase = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] )
57
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Any = logging.get_logger(__name__) class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """timm_backbone""" def __init__( self : Dict , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Any=3 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Tuple=None , **UpperCamelCase__ : Any , ) -> Any: """simple docstring""" super().__init__(**UpperCamelCase__ ) __magic_name__ = backbone __magic_name__ = num_channels __magic_name__ = features_only __magic_name__ = use_pretrained_backbone __magic_name__ = True __magic_name__ = out_indices if out_indices is not None else (-1,)
88
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class _UpperCamelCase ( pl.LightningModule ): '''simple docstring''' def __init__( self , __a ): super().__init__() __lowerCAmelCase = model __lowerCAmelCase = 2 __lowerCAmelCase = nn.Linear(self.model.config.hidden_size , self.num_labels ) def snake_case ( self ): pass def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = LongformerModel.from_pretrained(_UpperCamelCase ) __lowerCAmelCase = LightningModel(_UpperCamelCase ) __lowerCAmelCase = torch.load(_UpperCamelCase , map_location=torch.device("cpu" ) ) lightning_model.load_state_dict(ckpt["state_dict"] ) # init longformer question answering model __lowerCAmelCase = LongformerForQuestionAnswering.from_pretrained(_UpperCamelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(_UpperCamelCase ) print(f"Conversion successful. Model saved under {pytorch_dump_folder_path}" ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--longformer_model", default=None, type=str, required=True, help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.", ) parser.add_argument( "--longformer_question_answering_ckpt_path", default=None, type=str, required=True, help="Path the official PyTorch Lightning Checkpoint.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) A : Optional[int] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
57
0
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Optional[int] = FlaxAutoencoderKL @property def __lowercase ( self : str ): _a : Dict = 4 _a : Dict = 3 _a : str = (32, 32) _a : Tuple = jax.random.PRNGKey(0 ) _a : List[str] = jax.random.uniform(_UpperCAmelCase ,((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def __lowercase ( self : Tuple ): _a : Any = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } _a : Any = self.dummy_input return init_dict, inputs_dict
89
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = False while is_sorted is False: # Until all the indices are traversed keep looping __lowerCAmelCase = True for i in range(0 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False for i in range(1 , len(_UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowerCAmelCase , __lowerCAmelCase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowerCAmelCase = False return input_list if __name__ == "__main__": print("Enter list to be sorted") A : Union[str, Any] = [int(x) for x in input().split()] # inputing elements of the list in one line A : str = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
57
0
import numpy as np from transformers import Pipeline def lowerCamelCase_ ( UpperCamelCase__ : List[Any] ) -> Any: """simple docstring""" __lowerCamelCase = np.max(UpperCamelCase__ , axis=-1 , keepdims=UpperCamelCase__ ) __lowerCamelCase = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=UpperCamelCase__ ) class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" def lowercase_ ( self , **lowerCamelCase__ ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = {} if "second_text" in kwargs: __lowerCamelCase = kwargs['second_text'] return preprocess_kwargs, {}, {} def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__=None ) -> Tuple: '''simple docstring''' return self.tokenizer(lowerCamelCase__ , text_pair=lowerCamelCase__ , return_tensors=self.framework ) def lowercase_ ( self , lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.model(**lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ ) -> List[Any]: '''simple docstring''' __lowerCamelCase = model_outputs.logits[0].numpy() __lowerCamelCase = softmax(lowerCamelCase__ ) __lowerCamelCase = np.argmax(lowerCamelCase__ ) __lowerCamelCase = self.model.config.idalabel[best_class] __lowerCamelCase = probabilities[best_class].item() __lowerCamelCase = logits.tolist() return {"label": label, "score": score, "logits": logits}
90
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] =["""image_processor""", """tokenizer"""] __UpperCAmelCase : Optional[Any] ="""CLIPImageProcessor""" __UpperCAmelCase : Union[str, Any] =("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self , __a=None , __a=None , **__a ): __lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) __lowerCAmelCase = kwargs.pop("feature_extractor" ) __lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self , __a=None , __a=None , __a=None , **__a ): if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: __lowerCAmelCase = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: __lowerCAmelCase = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: __lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.batch_decode(*__a , **__a ) def snake_case ( self , *__a , **__a ): return self.tokenizer.decode(*__a , **__a ) @property def snake_case ( self ): __lowerCAmelCase = self.tokenizer.model_input_names __lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
57
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Tuple , **lowercase_ : Tuple): '''simple docstring''' warnings.warn( '''The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DonutImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class _UpperCamelCase : '''simple docstring''' pass
57
0
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json""", # See all Marian models at https://huggingface.co/models?filter=marian } class a__ ( snake_case__ ): _a : List[str] = """marian""" _a : Optional[int] = ["""past_key_values"""] _a : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , _A=5_8_1_0_1 , _A=None , _A=1_0_2_4 , _A=1_2 , _A=4_0_9_6 , _A=1_6 , _A=1_2 , _A=4_0_9_6 , _A=1_6 , _A=0.0 , _A=0.0 , _A=True , _A=True , _A="gelu" , _A=1_0_2_4 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.02 , _A=5_8_1_0_0 , _A=False , _A=5_8_1_0_0 , _A=0 , _A=0 , _A=True , **_A , ): """simple docstring""" __lowerCAmelCase = vocab_size __lowerCAmelCase = decoder_vocab_size or vocab_size __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = d_model __lowerCAmelCase = encoder_ffn_dim __lowerCAmelCase = encoder_layers __lowerCAmelCase = encoder_attention_heads __lowerCAmelCase = decoder_ffn_dim __lowerCAmelCase = decoder_layers __lowerCAmelCase = decoder_attention_heads __lowerCAmelCase = dropout __lowerCAmelCase = attention_dropout __lowerCAmelCase = activation_dropout __lowerCAmelCase = activation_function __lowerCAmelCase = init_std __lowerCAmelCase = encoder_layerdrop __lowerCAmelCase = decoder_layerdrop __lowerCAmelCase = use_cache __lowerCAmelCase = encoder_layers __lowerCAmelCase = scale_embedding # scale factor will be sqrt(d_model) if True __lowerCAmelCase = share_encoder_decoder_embeddings super().__init__( pad_token_id=_A , eos_token_id=_A , is_encoder_decoder=_A , decoder_start_token_id=_A , forced_eos_token_id=_A , **_A , ) class a__ ( snake_case__ ): @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: __lowerCAmelCase = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __lowerCAmelCase = {0: "batch"} __lowerCAmelCase = {0: "batch", 1: "past_decoder_sequence + sequence"} else: __lowerCAmelCase = {0: "batch", 1: "decoder_sequence"} __lowerCAmelCase = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(_A , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. __lowerCAmelCase = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __lowerCAmelCase , __lowerCAmelCase = self.num_layers for i in range(_A ): __lowerCAmelCase = {0: "batch", 2: "past_sequence + sequence"} __lowerCAmelCase = {0: "batch", 2: "past_sequence + sequence"} else: __lowerCAmelCase = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: __lowerCAmelCase = super().outputs else: __lowerCAmelCase = super(_A , self ).outputs if self.use_past: __lowerCAmelCase , __lowerCAmelCase = self.num_layers for i in range(_A ): __lowerCAmelCase = {0: "batch", 2: "past_sequence + sequence"} __lowerCAmelCase = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def __SCREAMING_SNAKE_CASE( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): """simple docstring""" __lowerCAmelCase = self._generate_dummy_inputs_for_encoder_and_decoder( _A , _A , _A , _A , _A ) # Generate decoder inputs __lowerCAmelCase = seq_length if not self.use_past else 1 __lowerCAmelCase = self._generate_dummy_inputs_for_encoder_and_decoder( _A , _A , _A , _A , _A ) __lowerCAmelCase = {f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()} __lowerCAmelCase = dict(**_A , **_A ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __lowerCAmelCase , __lowerCAmelCase = common_inputs["input_ids"].shape __lowerCAmelCase = common_inputs["decoder_input_ids"].shape[1] __lowerCAmelCase , __lowerCAmelCase = self.num_attention_heads __lowerCAmelCase = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __lowerCAmelCase = decoder_seq_length + 3 __lowerCAmelCase = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __lowerCAmelCase = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(_A , _A )] , dim=1 ) __lowerCAmelCase = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __lowerCAmelCase , __lowerCAmelCase = self.num_layers __lowerCAmelCase = min(_A , _A ) __lowerCAmelCase = max(_A , _A ) - min_num_layers __lowerCAmelCase = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(_A ): common_inputs["past_key_values"].append( ( torch.zeros(_A ), torch.zeros(_A ), torch.zeros(_A ), torch.zeros(_A ), ) ) # TODO: test this. __lowerCAmelCase = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(_A , _A ): common_inputs["past_key_values"].append((torch.zeros(_A ), torch.zeros(_A )) ) return common_inputs def __SCREAMING_SNAKE_CASE( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): """simple docstring""" __lowerCAmelCase = self._generate_dummy_inputs_for_encoder_and_decoder( _A , _A , _A , _A , _A ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __lowerCAmelCase , __lowerCAmelCase = common_inputs["input_ids"].shape # Not using the same length for past_key_values __lowerCAmelCase = seqlen + 2 __lowerCAmelCase , __lowerCAmelCase = self.num_layers __lowerCAmelCase , __lowerCAmelCase = self.num_attention_heads __lowerCAmelCase = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __lowerCAmelCase = common_inputs["attention_mask"].dtype __lowerCAmelCase = torch.cat( [common_inputs["attention_mask"], torch.ones(_A , _A , dtype=_A )] , dim=1 ) __lowerCAmelCase = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(_A ) ] return common_inputs def __SCREAMING_SNAKE_CASE( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): """simple docstring""" __lowerCAmelCase = compute_effective_axis_dimension( _A , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __lowerCAmelCase = tokenizer.num_special_tokens_to_add(_A ) __lowerCAmelCase = compute_effective_axis_dimension( _A , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_A ) # Generate dummy inputs according to compute batch and sequence __lowerCAmelCase = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size __lowerCAmelCase = dict(tokenizer(_A , return_tensors=_A ) ) return common_inputs def __SCREAMING_SNAKE_CASE( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: __lowerCAmelCase = self._generate_dummy_inputs_for_default_and_seqaseq_lm( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) else: __lowerCAmelCase = self._generate_dummy_inputs_for_causal_lm( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) return common_inputs def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" if self.task in ["default", "seq2seq-lm"]: __lowerCAmelCase = super()._flatten_past_key_values_(_A , _A , _A , _A ) else: __lowerCAmelCase = super(_A , self )._flatten_past_key_values_( _A , _A , _A , _A ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 1E-4
92
"""simple docstring""" import sys from collections import defaultdict class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): return self.node_position[vertex] def snake_case ( self , __a , __a ): __lowerCAmelCase = pos def snake_case ( self , __a , __a , __a , __a ): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCAmelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCAmelCase = 2 * start + 1 else: __lowerCAmelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCAmelCase , __lowerCAmelCase = heap[smallest_child], positions[smallest_child] __lowerCAmelCase , __lowerCAmelCase = ( heap[start], positions[start], ) __lowerCAmelCase , __lowerCAmelCase = temp, tempa __lowerCAmelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __a ) self.top_to_bottom(__a , __a , __a , __a ) def snake_case ( self , __a , __a , __a , __a ): __lowerCAmelCase = position[index] while index != 0: __lowerCAmelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCAmelCase = heap[parent] __lowerCAmelCase = position[parent] self.set_position(position[parent] , __a ) else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , __a ) break __lowerCAmelCase = parent else: __lowerCAmelCase = val __lowerCAmelCase = temp self.set_position(__a , 0 ) def snake_case ( self , __a , __a ): __lowerCAmelCase = len(__a ) // 2 - 1 for i in range(__a , -1 , -1 ): self.top_to_bottom(__a , __a , len(__a ) , __a ) def snake_case ( self , __a , __a ): __lowerCAmelCase = positions[0] __lowerCAmelCase = sys.maxsize self.top_to_bottom(__a , 0 , len(__a ) , __a ) return temp def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = Heap() __lowerCAmelCase = [0] * len(_UpperCamelCase ) __lowerCAmelCase = [-1] * len(_UpperCamelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCAmelCase = [] # Heap of Distance of vertices from their neighboring vertex __lowerCAmelCase = [] for vertex in range(len(_UpperCamelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_UpperCamelCase ) heap.node_position.append(_UpperCamelCase ) __lowerCAmelCase = [] __lowerCAmelCase = 1 __lowerCAmelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCAmelCase = 0 __lowerCAmelCase = distance heap.heapify(_UpperCamelCase , _UpperCamelCase ) for _ in range(1 , len(_UpperCamelCase ) ): __lowerCAmelCase = heap.delete_minimum(_UpperCamelCase , _UpperCamelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCAmelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_UpperCamelCase )] ): __lowerCAmelCase = distance heap.bottom_to_top( _UpperCamelCase , heap.get_position(_UpperCamelCase ) , _UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A : Optional[Any] = int(input("Enter number of edges: ").strip()) A : Dict = defaultdict(list) for _ in range(edges_number): A : str = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
57
0
'''simple docstring''' import argparse import os import re _lowercase : int = "src/transformers" # Pattern that looks at the indentation in a line. _lowercase : int = re.compile(r"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. _lowercase : Tuple = re.compile(r"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowercase : Dict = re.compile(r"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. _lowercase : Union[str, Any] = re.compile(r"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowercase : List[str] = re.compile(r"\[([^\]]+)\]") def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" lowercase_ : Any = _re_indent.search(__SCREAMING_SNAKE_CASE ) return "" if search is None else search.groups()[0] def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Tuple="" , __SCREAMING_SNAKE_CASE : Optional[Any]=None , __SCREAMING_SNAKE_CASE : Optional[Any]=None ): """simple docstring""" lowercase_ : Union[str, Any] = 0 lowercase_ : Dict = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(__SCREAMING_SNAKE_CASE ): index += 1 lowercase_ : int = ['''\n'''.join(lines[:index] )] else: lowercase_ : Optional[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowercase_ : Optional[Any] = [lines[index]] index += 1 while index < len(__SCREAMING_SNAKE_CASE ) and (end_prompt is None or not lines[index].startswith(__SCREAMING_SNAKE_CASE )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__SCREAMING_SNAKE_CASE ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) if index < len(__SCREAMING_SNAKE_CASE ) - 1: lowercase_ : Optional[Any] = [lines[index + 1]] index += 1 else: lowercase_ : Tuple = [] else: blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[Any] = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__SCREAMING_SNAKE_CASE ) > 0: blocks.append('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__SCREAMING_SNAKE_CASE ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" def _inner(__SCREAMING_SNAKE_CASE : Union[str, Any] ): return key(__SCREAMING_SNAKE_CASE ).lower().replace('''_''' , '''''' ) return _inner def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str]=None ): """simple docstring""" def noop(__SCREAMING_SNAKE_CASE : List[str] ): return x if key is None: lowercase_ : Optional[Any] = noop # Constants are all uppercase, they go first. lowercase_ : str = [obj for obj in objects if key(__SCREAMING_SNAKE_CASE ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowercase_ : str = [obj for obj in objects if key(__SCREAMING_SNAKE_CASE )[0].isupper() and not key(__SCREAMING_SNAKE_CASE ).isupper()] # Functions begin with a lowercase, they go last. lowercase_ : List[str] = [obj for obj in objects if not key(__SCREAMING_SNAKE_CASE )[0].isupper()] lowercase_ : str = ignore_underscore(__SCREAMING_SNAKE_CASE ) return sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) + sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) + sorted(__SCREAMING_SNAKE_CASE , key=__SCREAMING_SNAKE_CASE ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" def _replace(__SCREAMING_SNAKE_CASE : Dict ): lowercase_ : List[str] = match.groups()[0] if "," not in imports: return F'''[{imports}]''' lowercase_ : Union[str, Any] = [part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase_ : Dict = keys[:-1] return "[" + ", ".join([F'''"{k}"''' for k in sort_objects(__SCREAMING_SNAKE_CASE )] ) + "]" lowercase_ : List[str] = import_statement.split('''\n''' ) if len(__SCREAMING_SNAKE_CASE ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowercase_ : int = 2 if lines[1].strip() == '''[''' else 1 lowercase_ : Optional[int] = [(i, _re_strip_line.search(__SCREAMING_SNAKE_CASE ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowercase_ : str = sort_objects(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x[1] ) lowercase_ : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__SCREAMING_SNAKE_CASE ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowercase_ : int = _re_bracket_content.sub(_replace , lines[1] ) else: lowercase_ : str = [part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowercase_ : Optional[int] = keys[:-1] lowercase_ : str = get_indent(lines[1] ) + ''', '''.join([F'''"{k}"''' for k in sort_objects(__SCREAMING_SNAKE_CASE )] ) return "\n".join(__SCREAMING_SNAKE_CASE ) else: # Finally we have to deal with imports fitting on one line lowercase_ : List[str] = _re_bracket_content.sub(_replace , __SCREAMING_SNAKE_CASE ) return import_statement def snake_case_ ( __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Any=True ): """simple docstring""" with open(__SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as f: lowercase_ : Optional[int] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowercase_ : Dict = split_code_in_indented_blocks( __SCREAMING_SNAKE_CASE , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__SCREAMING_SNAKE_CASE ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowercase_ : Dict = main_blocks[block_idx] lowercase_ : str = block.split('''\n''' ) # Get to the start of the imports. lowercase_ : Any = 0 while line_idx < len(__SCREAMING_SNAKE_CASE ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowercase_ : Dict = len(__SCREAMING_SNAKE_CASE ) else: line_idx += 1 if line_idx >= len(__SCREAMING_SNAKE_CASE ): continue # Ignore beginning and last line: they don't contain anything. lowercase_ : Any = '''\n'''.join(block_lines[line_idx:-1] ) lowercase_ : Tuple = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowercase_ : Tuple = split_code_in_indented_blocks(__SCREAMING_SNAKE_CASE , indent_level=__SCREAMING_SNAKE_CASE ) # We have two categories of import key: list or _import_structure[key].append/extend lowercase_ : str = _re_direct_key if '''_import_structure = {''' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowercase_ : Optional[int] = [(pattern.search(__SCREAMING_SNAKE_CASE ).groups()[0] if pattern.search(__SCREAMING_SNAKE_CASE ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowercase_ : List[str] = [(i, key) for i, key in enumerate(__SCREAMING_SNAKE_CASE ) if key is not None] lowercase_ : Optional[Any] = [x[0] for x in sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowercase_ : int = 0 lowercase_ : Union[str, Any] = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: lowercase_ : Optional[Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(__SCREAMING_SNAKE_CASE ) count += 1 # And we put our main block back together with its first and last line. lowercase_ : int = '''\n'''.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(__SCREAMING_SNAKE_CASE ): if check_only: return True else: print(F'''Overwriting {file}.''' ) with open(__SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write('''\n'''.join(__SCREAMING_SNAKE_CASE ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int]=True ): """simple docstring""" lowercase_ : str = [] for root, _, files in os.walk(__SCREAMING_SNAKE_CASE ): if "__init__.py" in files: lowercase_ : Optional[Any] = sort_imports(os.path.join(__SCREAMING_SNAKE_CASE , '''__init__.py''' ) , check_only=__SCREAMING_SNAKE_CASE ) if result: lowercase_ : List[str] = [os.path.join(__SCREAMING_SNAKE_CASE , '''__init__.py''' )] if len(__SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F'''Would overwrite {len(__SCREAMING_SNAKE_CASE )} files, run `make style`.''' ) if __name__ == "__main__": _lowercase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") _lowercase : Any = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
93
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() A : Tuple = logging.get_logger(__name__) A : Tuple = [ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] A : Optional[Any] = [ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = torch.load(_UpperCamelCase , map_location="cpu" ) return sd def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=rename_keys_prefix ): '''simple docstring''' __lowerCAmelCase = OrderedDict() __lowerCAmelCase = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue __lowerCAmelCase = key for name_pair in rename_keys_prefix: __lowerCAmelCase = new_key.replace(name_pair[0] , name_pair[1] ) __lowerCAmelCase = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately __lowerCAmelCase = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}." # Get Config if "pre" in checkpoint_path: __lowerCAmelCase = "pretraining" if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 1024} else: raise NotImplementedError(f"No implementation found for `{checkpoint_path}`." ) else: if "vcr" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 512} __lowerCAmelCase = "multichoice" elif "vqa_advanced" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048} __lowerCAmelCase = "vqa_advanced" elif "vqa" in checkpoint_path: __lowerCAmelCase = {"visual_embedding_dim": 2048, "num_labels": 3129} __lowerCAmelCase = "vqa" elif "nlvr" in checkpoint_path: __lowerCAmelCase = { "visual_embedding_dim": 1024, "num_labels": 2, } __lowerCAmelCase = "nlvr" __lowerCAmelCase = VisualBertConfig(**_UpperCamelCase ) # Load State Dict __lowerCAmelCase = load_state_dict(_UpperCamelCase ) __lowerCAmelCase = get_new_dict(_UpperCamelCase , _UpperCamelCase ) if model_type == "pretraining": __lowerCAmelCase = VisualBertForPreTraining(_UpperCamelCase ) elif model_type == "vqa": __lowerCAmelCase = VisualBertForQuestionAnswering(_UpperCamelCase ) elif model_type == "nlvr": __lowerCAmelCase = VisualBertForVisualReasoning(_UpperCamelCase ) elif model_type == "multichoice": __lowerCAmelCase = VisualBertForMultipleChoice(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Save Checkpoints Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") A : Optional[int] = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
57
0
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class _snake_case : def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=10 , _lowerCamelCase=3 , _lowerCamelCase=2 , _lowerCamelCase=2 , _lowerCamelCase=2 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=32 , _lowerCamelCase=5 , _lowerCamelCase=4 , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=10 , _lowerCamelCase=0.02 , _lowerCamelCase=0.9 , _lowerCamelCase=None , ): a :Union[str, Any] = parent a :str = batch_size a :Optional[int] = image_size a :int = num_channels a :Any = patch_size a :Optional[int] = tubelet_size a :int = num_frames a :Optional[Any] = is_training a :Union[str, Any] = use_labels a :List[str] = hidden_size a :str = num_hidden_layers a :int = num_attention_heads a :int = intermediate_size a :List[Any] = hidden_act a :Dict = hidden_dropout_prob a :List[str] = attention_probs_dropout_prob a :Tuple = type_sequence_label_size a :Optional[Any] = initializer_range a :Dict = mask_ratio a :List[Any] = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame a :List[Any] = (image_size // patch_size) ** 2 a :List[Any] = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos a :List[str] = int(mask_ratio * self.seq_length ) def SCREAMING_SNAKE_CASE__ ( self ): a :Any = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) a :List[str] = None if self.use_labels: a :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a :int = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self ): return VideoMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): a :List[str] = VideoMAEModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() a :Dict = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): a :Optional[Any] = VideoMAEForPreTraining(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch a :Optional[Any] = torch.ones((self.num_masks,) ) a :str = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] ) a :List[str] = mask.expand(self.batch_size , -1 ).bool() a :Optional[int] = model(_lowerCamelCase , _lowerCamelCase ) # model only returns predictions for masked patches a :Optional[Any] = mask.sum().item() a :Union[str, Any] = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) ) def SCREAMING_SNAKE_CASE__ ( self ): a :str = self.prepare_config_and_inputs() a , a , a :Union[str, Any] = config_and_inputs a :Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class _snake_case ( _snake_case , _snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE__ = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = ( {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def SCREAMING_SNAKE_CASE__ ( self ): a :List[Any] = VideoMAEModelTester(self ) a :Any = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=False ): a :List[Any] = copy.deepcopy(_lowerCamelCase ) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch a :Tuple = torch.ones((self.model_tester.num_masks,) ) a :Optional[Any] = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] ) a :Optional[int] = mask.expand(self.model_tester.batch_size , -1 ).bool() a :List[str] = bool_masked_pos.to(_lowerCamelCase ) if return_labels: if model_class in [ *get_values(_lowerCamelCase ), ]: a :List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_lowerCamelCase ) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''VideoMAE does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE__ ( self ): pass def SCREAMING_SNAKE_CASE__ ( self ): a , a :Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a :Optional[int] = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a :Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def SCREAMING_SNAKE_CASE__ ( self ): a , a :str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a :Union[str, Any] = model_class(_lowerCamelCase ) a :Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a :Any = [*signature.parameters.keys()] a :str = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ): a :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ): a :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE__ ( self ): for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a :Optional[Any] = VideoMAEModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ): if not self.has_attentions: pass else: a , a :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() a :List[Any] = True for model_class in self.all_model_classes: a :Union[str, Any] = self.model_tester.seq_length - self.model_tester.num_masks a :List[Any] = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) a :Dict = True a :Dict = False a :List[Any] = True a :str = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): a :Any = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) a :Union[str, Any] = outputs.attentions self.assertEqual(len(_lowerCamelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] a :Union[str, Any] = True a :List[str] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): a :Tuple = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) a :Tuple = outputs.attentions self.assertEqual(len(_lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) a :List[str] = len(_lowerCamelCase ) # Check attention is always last and order is fine a :Tuple = True a :str = True a :List[Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): a :List[Any] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) self.assertEqual(out_len + 1 , len(_lowerCamelCase ) ) a :int = outputs.attentions self.assertEqual(len(_lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def SCREAMING_SNAKE_CASE__ ( self ): def check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): a :Optional[Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): a :List[Any] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) a :List[Any] = outputs.hidden_states a :int = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) a :int = self.model_tester.seq_length - self.model_tester.num_masks a :Dict = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) a , a :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a :Optional[Any] = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a :Tuple = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE__ ( self ): pass def __lowerCamelCase ( ): """simple docstring""" a :Optional[Any] = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' ) a :Optional[Any] = np.load(UpperCAmelCase_ ) return list(UpperCAmelCase_ ) @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ): # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self ): a :List[Any] = VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics''' ).to( _lowerCamelCase ) a :Tuple = self.default_image_processor a :Optional[int] = prepare_video() a :str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): a :Tuple = model(**_lowerCamelCase ) # verify the logits a :List[str] = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) a :Optional[int] = torch.tensor([0.3669, -0.0688, -0.2421] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ): a :str = VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''' ).to(_lowerCamelCase ) a :str = self.default_image_processor a :List[str] = prepare_video() a :Union[str, Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # add boolean mask, indicating which patches to mask a :Union[str, Any] = hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos''' , filename='''bool_masked_pos.pt''' ) a :Dict = torch.load(_lowerCamelCase ) # forward pass with torch.no_grad(): a :Optional[Any] = model(**_lowerCamelCase ) # verify the logits a :List[Any] = torch.Size([1, 1408, 1536] ) a :Union[str, Any] = torch.tensor( [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] , device=_lowerCamelCase ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify the loss (`config.norm_pix_loss` = `True`) a :Union[str, Any] = torch.tensor([0.5142] , device=_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.loss , _lowerCamelCase , atol=1e-4 ) ) # verify the loss (`config.norm_pix_loss` = `False`) a :List[str] = VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''' , norm_pix_loss=_lowerCamelCase ).to( _lowerCamelCase ) with torch.no_grad(): a :Tuple = model(**_lowerCamelCase ) a :Optional[Any] = torch.tensor(torch.tensor([0.6469] ) , device=_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.loss , _lowerCamelCase , atol=1e-4 ) )
94
"""simple docstring""" class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' pass class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [ [], [], [], ] def snake_case ( self , __a , __a ): try: if len(self.queues[priority] ) >= 1_00: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(__a ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def snake_case ( self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues ) ) class _UpperCamelCase : '''simple docstring''' def __init__( self ): __lowerCAmelCase = [] def snake_case ( self , __a ): if len(self.queue ) == 1_00: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(__a ) def snake_case ( self ): if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(__a ) return data def __str__( self ): return str(self.queue ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(_UpperCamelCase ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(_UpperCamelCase ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
57
0
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home UpperCAmelCase : Tuple = HUGGINGFACE_HUB_CACHE UpperCAmelCase : Union[str, Any] = """config.json""" UpperCAmelCase : Union[str, Any] = """diffusion_pytorch_model.bin""" UpperCAmelCase : Optional[Any] = """diffusion_flax_model.msgpack""" UpperCAmelCase : Optional[int] = """model.onnx""" UpperCAmelCase : int = """diffusion_pytorch_model.safetensors""" UpperCAmelCase : List[Any] = """weights.pb""" UpperCAmelCase : Optional[int] = """https://huggingface.co""" UpperCAmelCase : str = default_cache_path UpperCAmelCase : str = """diffusers_modules""" UpperCAmelCase : int = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) UpperCAmelCase : Dict = ["""fp16""", """non-ema"""] UpperCAmelCase : List[str] = """.self_attn"""
95
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' 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\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) __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()
57
0
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () lowercase__ = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). lowercase__ = [0, 25, 50] lowercase__ = [25, 50, 75] lowercase__ = fuzz.membership.trimf(X, abca) lowercase__ = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. lowercase__ = np.ones(75) lowercase__ = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) lowercase__ = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) lowercase__ = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) lowercase__ = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) lowercase__ = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] lowercase__ = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) lowercase__ = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] lowercase__ = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] lowercase__ = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title("""Young""") plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title("""Middle aged""") plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title("""union""") plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title("""intersection""") plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title("""complement_a""") plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title("""difference a/b""") plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title("""alg_sum""") plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title("""alg_product""") plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title("""bdd_sum""") plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title("""bdd_difference""") plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
96
"""simple docstring""" def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = 1 while len(_UpperCamelCase ) < 1e6: constant.append(str(_UpperCamelCase ) ) i += 1 __lowerCAmelCase = "".join(_UpperCamelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[9_9999] ) * int(constant[99_9999] ) ) if __name__ == "__main__": print(solution())
57
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_=2 , UpperCamelCase_=3 , UpperCamelCase_=64 , UpperCamelCase_=None ): '''simple docstring''' UpperCamelCase__ :Optional[int] = np.random.default_rng(UpperCamelCase_ ) UpperCamelCase__ :Tuple = length UpperCamelCase__ :Optional[int] = rng.normal(size=(length,) ).astype(np.floataa ) UpperCamelCase__ :str = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ): '''simple docstring''' return self.length def __getitem__( self , UpperCamelCase_ ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class lowercase ( torch.nn.Module ): """simple docstring""" def __init__( self , UpperCamelCase_=0 , UpperCamelCase_=0 , UpperCamelCase_=False ): '''simple docstring''' super().__init__() UpperCamelCase__ :Tuple = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCamelCase__ :List[str] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCamelCase__ :Tuple = True def lowerCAmelCase__ ( self , UpperCamelCase_=None ): '''simple docstring''' if self.first_batch: print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCamelCase__ :Tuple = False return x * self.a[0] + self.b[0] class lowercase ( torch.nn.Module ): """simple docstring""" def __init__( self , UpperCamelCase_=0 , UpperCamelCase_=0 , UpperCamelCase_=False ): '''simple docstring''' super().__init__() UpperCamelCase__ :List[str] = torch.nn.Parameter(torch.tensor(UpperCamelCase_ ).float() ) UpperCamelCase__ :List[Any] = torch.nn.Parameter(torch.tensor(UpperCamelCase_ ).float() ) UpperCamelCase__ :str = True def lowerCAmelCase__ ( self , UpperCamelCase_=None ): '''simple docstring''' if self.first_batch: print(F'''Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}''' ) UpperCamelCase__ :Optional[int] = False return x * self.a + self.b def a ( __a , __a = 16 ) -> Union[str, Any]: '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer UpperCamelCase__ :Any = AutoTokenizer.from_pretrained('''bert-base-cased''' ) UpperCamelCase__ :Tuple = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} UpperCamelCase__ :Dict = load_dataset('''csv''' , data_files=__a ) UpperCamelCase__ :int = datasets['''train'''].unique('''label''' ) UpperCamelCase__ :List[str] = {v: i for i, v in enumerate(__a )} def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase__ :Any = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__a , max_length=__a , padding='''max_length''' ) if "label" in examples: UpperCamelCase__ :str = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase__ :str = datasets.map( __a , batched=__a , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__a ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__a , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(__a , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. UpperCamelCase__ :int = DataLoader(tokenized_datasets['''train'''] , shuffle=__a , collate_fn=__a , batch_size=2 ) UpperCamelCase__ :Dict = DataLoader(tokenized_datasets['''validation'''] , shuffle=__a , collate_fn=__a , batch_size=1 ) return train_dataloader, eval_dataloader
97
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs A : Union[str, Any] = imread(R"digital_image_processing/image_data/lena_small.jpg") A : Optional[Any] = cvtColor(img, COLOR_BGR2GRAY) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = cn.convert_to_negative(_UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def _lowerCamelCase ( ): '''simple docstring''' with Image.open("digital_image_processing/image_data/lena_small.jpg" ) as img: # Work around assertion for response assert str(cc.change_contrast(_UpperCamelCase , 110 ) ).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = imread("digital_image_processing/image_data/lena_small.jpg" , 0 ) # assert ambiguous array for all == True assert canny_img.all() __lowerCAmelCase = canny.canny(_UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def _lowerCamelCase ( ): '''simple docstring''' assert gg.gaussian_filter(_UpperCamelCase , 5 , sigma=0.9 ).all() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __lowerCAmelCase = conv.img_convolve(_UpperCamelCase , _UpperCamelCase ).astype(_UpperCamelCase ) assert res.any() def _lowerCamelCase ( ): '''simple docstring''' assert med.median_filter(_UpperCamelCase , 3 ).any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase , __lowerCAmelCase = sob.sobel_filter(_UpperCamelCase ) assert grad.any() and theta.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = sp.make_sepia(_UpperCamelCase , 20 ) assert sepia.all() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' __lowerCAmelCase = bs.Burkes(imread(_UpperCamelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def _lowerCamelCase ( _UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' __lowerCAmelCase = rs.NearestNeighbour(imread(_UpperCamelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. __lowerCAmelCase = imread(_UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = image[x_coordinate][y_coordinate] __lowerCAmelCase = lbp.get_neighbors_pixel( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __lowerCAmelCase = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __lowerCAmelCase = lbp.local_binary_value(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) assert lbp_image.any()
57
0
"""simple docstring""" import argparse lowerCAmelCase__ : List[str] = 'docs/source/_static/js/custom.js' def a_ ( lowerCamelCase ): with open(lowerCamelCase , encoding='utf-8' , newline='\n' ) as f: UpperCAmelCase__ = f.readlines() UpperCAmelCase__ = 0 # First let's put the right version while not lines[index].startswith('const stableVersion =' ): index += 1 UpperCAmelCase__ = f'''const stableVersion = "v{version}"\n''' # Then update the dictionary while not lines[index].startswith('const versionMapping = {' ): index += 1 # We go until the end while not lines[index].startswith('}' ): index += 1 # We add the new version at the end lines[index - 1] += f''' "v{version}": "v{version}",\n''' with open(lowerCamelCase , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(lowerCamelCase ) if __name__ == "__main__": lowerCAmelCase__ : List[Any] = argparse.ArgumentParser() parser.add_argument('--version', help='Release version.') lowerCAmelCase__ : Optional[int] = parser.parse_args() update_custom_js(args.version)
98
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A : Optional[int] = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltCLIPTextConfig", "AltCLIPVisionConfig", ], "processing_altclip": ["AltCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = [ "ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "AltCLIPPreTrainedModel", "AltCLIPModel", "AltCLIPTextModel", "AltCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys A : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A__ ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : Optional[int] = ShapEImgaImgPipeline __A : Tuple = ['''image'''] __A : Any = ['''image'''] __A : Optional[Any] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __A : Dict = False @property def __lowercase ( self) -> Any: '''simple docstring''' return 32 @property def __lowercase ( self) -> Optional[int]: '''simple docstring''' return 32 @property def __lowercase ( self) -> Optional[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' return 8 @property def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0) a__ : Any = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) a__ : Dict = CLIPVisionModel(lowercase) return model @property def __lowercase ( self) -> List[Any]: '''simple docstring''' a__ : str = CLIPImageProcessor( crop_size=224 , do_center_crop=lowercase , do_normalize=lowercase , do_resize=lowercase , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=224 , ) return image_processor @property def __lowercase ( self) -> str: '''simple docstring''' torch.manual_seed(0) a__ : str = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'embedding_proj_norm_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } a__ : Any = PriorTransformer(**lowercase) return model @property def __lowercase ( self) -> Any: '''simple docstring''' torch.manual_seed(0) a__ : List[Any] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } a__ : List[str] = ShapERenderer(**lowercase) return model def __lowercase ( self) -> str: '''simple docstring''' a__ : Dict = self.dummy_prior a__ : List[str] = self.dummy_image_encoder a__ : int = self.dummy_image_processor a__ : str = self.dummy_renderer a__ : Optional[int] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=lowercase , clip_sample=lowercase , clip_sample_range=1.0 , ) a__ : List[Any] = { 'prior': prior, 'image_encoder': image_encoder, 'image_processor': image_processor, 'renderer': renderer, 'scheduler': scheduler, } return components def __lowercase ( self , lowercase , lowercase=0) -> List[str]: '''simple docstring''' a__ : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowercase)).to(lowercase) if str(lowercase).startswith('mps'): a__ : List[str] = torch.manual_seed(lowercase) else: a__ : str = torch.Generator(device=lowercase).manual_seed(lowercase) a__ : Tuple = { 'image': input_image, 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def __lowercase ( self) -> Any: '''simple docstring''' a__ : int = 'cpu' a__ : List[str] = self.get_dummy_components() a__ : Dict = self.pipeline_class(**lowercase) a__ : Optional[int] = pipe.to(lowercase) pipe.set_progress_bar_config(disable=lowercase) a__ : Tuple = pipe(**self.get_dummy_inputs(lowercase)) a__ : Any = output.images[0] a__ : Any = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a__ : List[str] = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def __lowercase ( self) -> Any: '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2]) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : str = torch_device == 'cpu' a__ : Tuple = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=lowercase , relax_max_difference=lowercase , ) def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : List[str] = self.get_dummy_components() a__ : str = self.pipeline_class(**lowercase) a__ : List[str] = pipe.to(lowercase) pipe.set_progress_bar_config(disable=lowercase) a__ : Optional[Any] = 1 a__ : List[str] = 2 a__ : Optional[Any] = self.get_dummy_inputs(lowercase) for key in inputs.keys(): if key in self.batch_params: a__ : Any = batch_size * [inputs[key]] a__ : int = pipe(**lowercase , num_images_per_prompt=lowercase)[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self) -> Dict: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self) -> Dict: '''simple docstring''' a__ : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/corgi.png') a__ : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_img2img_out.npy') a__ : List[str] = ShapEImgaImgPipeline.from_pretrained('openai/shap-e-img2img') a__ : Tuple = pipe.to(lowercase) pipe.set_progress_bar_config(disable=lowercase) a__ : List[Any] = torch.Generator(device=lowercase).manual_seed(0) a__ : Optional[int] = pipe( lowercase , generator=lowercase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(lowercase , lowercase)
99
"""simple docstring""" import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments A : Dict = logging.getLogger(__name__) @dataclass class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : Optional[float] =field( default=0.0 ,metadata={"""help""": """The label smoothing epsilon to apply (if not zero)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """Whether to SortishSamler or not."""} ) __UpperCAmelCase : bool =field( default=lowerCAmelCase__ ,metadata={"""help""": """Whether to use generate to calculate generative metrics (ROUGE, BLEU)."""} ) __UpperCAmelCase : bool =field(default=lowerCAmelCase__ ,metadata={"""help""": """whether to use adafactor"""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Encoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Decoder layer dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field(default=lowerCAmelCase__ ,metadata={"""help""": """Dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[float] =field( default=lowerCAmelCase__ ,metadata={"""help""": """Attention dropout probability. Goes into model.config."""} ) __UpperCAmelCase : Optional[str] =field( default="""linear""" ,metadata={"""help""": F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} ,)
57
0
"""simple docstring""" import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" __lowercase : str = '''char''' __lowercase : int = '''bpe''' __lowercase : Tuple = '''wp''' __magic_name__ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" __lowercase : Tuple = ['''image_processor''', '''char_tokenizer'''] __lowercase : Dict = '''ViTImageProcessor''' __lowercase : Union[str, Any] = '''MgpstrTokenizer''' def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__): __SCREAMING_SNAKE_CASE = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE = kwargs.pop("""feature_extractor""") __SCREAMING_SNAKE_CASE = 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`.""") __SCREAMING_SNAKE_CASE = tokenizer __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""gpt2""") __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""bert-base-uncased""") super().__init__(lowerCAmelCase__ , lowerCAmelCase__) def __call__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__): if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""") if images is not None: __SCREAMING_SNAKE_CASE = self.image_processor(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__) if text is not None: __SCREAMING_SNAKE_CASE = self.char_tokenizer(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__) if text is None: return inputs elif images is None: return encodings else: __SCREAMING_SNAKE_CASE = encodings["""input_ids"""] return inputs def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = sequences __SCREAMING_SNAKE_CASE = char_preds.size(0) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self._decode_helper(lowerCAmelCase__ , """char""") __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self._decode_helper(lowerCAmelCase__ , """bpe""") __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = self._decode_helper(lowerCAmelCase__ , """wp""") __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for i in range(lowerCAmelCase__): __SCREAMING_SNAKE_CASE = [char_scores[i], bpe_scores[i], wp_scores[i]] __SCREAMING_SNAKE_CASE = [char_strs[i], bpe_strs[i], wp_strs[i]] __SCREAMING_SNAKE_CASE = scores.index(max(lowerCAmelCase__)) final_strs.append(strs[max_score_index]) final_scores.append(scores[max_score_index]) __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = final_strs __SCREAMING_SNAKE_CASE = final_scores __SCREAMING_SNAKE_CASE = char_strs __SCREAMING_SNAKE_CASE = bpe_strs __SCREAMING_SNAKE_CASE = wp_strs return out def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__): if format == DecodeType.CHARACTER: __SCREAMING_SNAKE_CASE = self.char_decode __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = """[s]""" elif format == DecodeType.BPE: __SCREAMING_SNAKE_CASE = self.bpe_decode __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = """#""" elif format == DecodeType.WORDPIECE: __SCREAMING_SNAKE_CASE = self.wp_decode __SCREAMING_SNAKE_CASE = 1_0_2 __SCREAMING_SNAKE_CASE = """[SEP]""" else: raise ValueError(f"Format {format} is not supported.") __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = [], [] __SCREAMING_SNAKE_CASE = pred_logits.size(0) __SCREAMING_SNAKE_CASE = pred_logits.size(1) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = pred_logits.topk(1 , dim=-1 , largest=lowerCAmelCase__ , sorted=lowerCAmelCase__) __SCREAMING_SNAKE_CASE = preds_index.view(-1 , lowerCAmelCase__)[:, 1:] __SCREAMING_SNAKE_CASE = decoder(lowerCAmelCase__) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = torch.nn.functional.softmax(lowerCAmelCase__ , dim=2).max(dim=2) __SCREAMING_SNAKE_CASE = preds_max_prob[:, 1:] for index in range(lowerCAmelCase__): __SCREAMING_SNAKE_CASE = preds_str[index].find(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = preds_str[index][:pred_eos] __SCREAMING_SNAKE_CASE = preds_index[index].cpu().tolist() __SCREAMING_SNAKE_CASE = pred_index.index(lowerCAmelCase__) if eos_token in pred_index else -1 __SCREAMING_SNAKE_CASE = preds_max_prob[index][: pred_eos_index + 1] __SCREAMING_SNAKE_CASE = pred_max_prob.cumprod(dim=0)[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(lowerCAmelCase__) conf_scores.append(lowerCAmelCase__) return dec_strs, conf_scores def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = [seq.replace(""" """ , """""") for seq in self.char_tokenizer.batch_decode(lowerCAmelCase__)] return decode_strs def snake_case_ ( self , lowerCAmelCase__): return self.bpe_tokenizer.batch_decode(lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = [seq.replace(""" """ , """""") for seq in self.wp_tokenizer.batch_decode(lowerCAmelCase__)] return decode_strs
100
"""simple docstring""" import argparse import os import re import packaging.version A : Any = "examples/" A : Optional[Any] = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } A : Optional[int] = { "init": "src/transformers/__init__.py", "setup": "setup.py", } A : List[Any] = "README.md" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , _UpperCamelCase ) __lowerCAmelCase = re_pattern.sub(_UpperCamelCase , _UpperCamelCase ) with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' for folder, directories, fnames in os.walk(_UpperCamelCase ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(_UpperCamelCase , _UpperCamelCase ) , _UpperCamelCase , pattern="examples" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=False ): '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if not patch: update_version_in_examples(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(_UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(_UpperCamelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(_UpperCamelCase ) def _lowerCamelCase ( ): '''simple docstring''' with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(_UpperCamelCase ).groups()[0] return packaging.version.parse(_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase=False ): '''simple docstring''' __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __lowerCAmelCase = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(f"Which version are you releasing? [{default_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = default_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase , patch=_UpperCamelCase ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _lowerCamelCase ( ): '''simple docstring''' __lowerCAmelCase = get_version() __lowerCAmelCase = f"{current_version.major}.{current_version.minor + 1}.0.dev0" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(f"Which version are we developing now? [{dev_version}]" ) if len(_UpperCamelCase ) == 0: __lowerCAmelCase = dev_version print(f"Updating version to {version}." ) global_version_update(_UpperCamelCase ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": A : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") A : Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
57
0