code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import logging from transformers.configuration_utils import PretrainedConfig SCREAMING_SNAKE_CASE__ = logging.getLogger(__name__) class a_ ( lowerCamelCase ): lowercase = """masked_bert""" def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-12 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE="topK" , _SCREAMING_SNAKE_CASE="constant" , _SCREAMING_SNAKE_CASE=0.0 , **_SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" super().__init__(pad_token_id=lowercase_ , **lowercase_ ) UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = pruning_method UpperCamelCase = mask_init UpperCamelCase = mask_scale
715
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: UpperCamelCase = len(snake_case__ ) UpperCamelCase = len(snake_case__ ) UpperCamelCase = ( first_str_length if first_str_length > second_str_length else second_str_length ) UpperCamelCase = [] for char_count in range(snake_case__ ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(snake_case__ ) if __name__ == "__main__": print(alternative_string_arrange('AB', 'XYZ'), end=' ')
716
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> str: if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase = """""" while len(__UpperCamelCase ) % 3 != 0: UpperCamelCase = """0""" + bin_string UpperCamelCase = [ bin_string[index : index + 3] for index in range(len(__UpperCamelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase = 0 for index, val in enumerate(__UpperCamelCase ): oct_val += int(2 ** (2 - index) * int(__UpperCamelCase ) ) oct_string += str(__UpperCamelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' from __future__ import annotations SCREAMING_SNAKE_CASE__ = 8.9_88E9 # units = N * m^s * C^-2 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> dict[str, float]: UpperCamelCase = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if distance < 0: raise ValueError("""Distance cannot be negative""" ) if force == 0: UpperCamelCase = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: UpperCamelCase = abs(__UpperCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: UpperCamelCase = abs(__UpperCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: UpperCamelCase = (COULOMBS_CONSTANT * charge_product / abs(__UpperCamelCase )) ** 0.5 return {"distance": distance} raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
717
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowercase__ ( __UpperCamelCase=None )-> Union[str, Any]: if subparsers is not None: UpperCamelCase = subparsers.add_parser("""env""" ) else: UpperCamelCase = argparse.ArgumentParser("""Accelerate env command""" ) parser.add_argument( """--config_file""" , default=__UpperCamelCase , help="""The config file to use for the default values in the launching script.""" ) if subparsers is not None: parser.set_defaults(func=__UpperCamelCase ) return parser def lowercase__ ( __UpperCamelCase )-> List[str]: UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = is_xpu_available() UpperCamelCase = is_npu_available() UpperCamelCase = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(__UpperCamelCase ): UpperCamelCase = load_config_from_file(args.config_file ).to_dict() UpperCamelCase = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """PyTorch XPU available""": str(__UpperCamelCase ), """PyTorch NPU available""": str(__UpperCamelCase ), """System RAM""": F"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", } if pt_cuda_available: UpperCamelCase = torch.cuda.get_device_name() print("""\nCopy-and-paste the text below in your GitHub issue\n""" ) print("""\n""".join([F"- {prop}: {val}" for prop, val in info.items()] ) ) print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" ) UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else F"\t{accelerate_config}" ) print(__UpperCamelCase ) UpperCamelCase = accelerate_config return info def lowercase__ ( )-> int: UpperCamelCase = env_command_parser() UpperCamelCase = parser.parse_args() env_command(__UpperCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
35
0
'''simple docstring''' import os # Precomputes a list of the 100 first triangular numbers SCREAMING_SNAKE_CASE__ = [int(0.5 * n * (n + 1)) for n in range(1, 1_0_1)] def lowercase__ ( )-> Union[str, Any]: UpperCamelCase = os.path.dirname(os.path.realpath(__UpperCamelCase ) ) UpperCamelCase = os.path.join(__UpperCamelCase , """words.txt""" ) UpperCamelCase = "" with open(__UpperCamelCase ) as f: UpperCamelCase = f.readline() UpperCamelCase = [word.strip("""\"""" ) for word in words.strip("""\r\n""" ).split(""",""" )] UpperCamelCase = [ word for word in [sum(ord(__UpperCamelCase ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(__UpperCamelCase ) if __name__ == "__main__": print(solution())
718
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) UpperCamelCase = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__UpperCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
35
0
def lowercase__ ( __UpperCamelCase )-> Any: UpperCamelCase = [] if len(__a ) == 1: return [nums.copy()] for _ in range(len(__a ) ): UpperCamelCase = nums.pop(0 ) UpperCamelCase = permute(__a ) for perm in permutations: perm.append(__a ) result.extend(__a ) nums.append(__a ) return result def lowercase__ ( __UpperCamelCase )-> Dict: def backtrack(__UpperCamelCase ): if start == len(__a ) - 1: output.append(nums[:] ) else: for i in range(__a , len(__a ) ): UpperCamelCase ,UpperCamelCase = nums[i], nums[start] backtrack(start + 1 ) UpperCamelCase ,UpperCamelCase = nums[i], nums[start] # backtrack UpperCamelCase = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function SCREAMING_SNAKE_CASE__ = permutea([1, 2, 3]) print(res) doctest.testmod()
719
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowercase__ ( __UpperCamelCase , __UpperCamelCase=1 )-> Tuple: if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> Dict: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item.replace("""in_layers.0""" , """norm1""" ) UpperCamelCase = new_item.replace("""in_layers.2""" , """conv1""" ) UpperCamelCase = new_item.replace("""out_layers.0""" , """norm2""" ) UpperCamelCase = new_item.replace("""out_layers.3""" , """conv2""" ) UpperCamelCase = new_item.replace("""emb_layers.1""" , """time_emb_proj""" ) UpperCamelCase = new_item.replace("""skip_connection""" , """conv_shortcut""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> List[str]: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item UpperCamelCase = new_item.replace("""norm.weight""" , """group_norm.weight""" ) UpperCamelCase = new_item.replace("""norm.bias""" , """group_norm.bias""" ) UpperCamelCase = new_item.replace("""proj_out.weight""" , """proj_attn.weight""" ) UpperCamelCase = new_item.replace("""proj_out.bias""" , """proj_attn.bias""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None )-> str: assert isinstance(__UpperCamelCase , __UpperCamelCase ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): UpperCamelCase = old_checkpoint[path] UpperCamelCase = old_tensor.shape[0] // 3 UpperCamelCase = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) UpperCamelCase = old_tensor.shape[0] // config["""num_head_channels"""] // 3 UpperCamelCase = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = old_tensor.split(channels // num_heads , dim=1 ) UpperCamelCase = query.reshape(__UpperCamelCase ) UpperCamelCase = key.reshape(__UpperCamelCase ) UpperCamelCase = value.reshape(__UpperCamelCase ) for path in paths: UpperCamelCase = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here UpperCamelCase = new_path.replace("""middle_block.0""" , """mid_block.resnets.0""" ) UpperCamelCase = new_path.replace("""middle_block.1""" , """mid_block.attentions.0""" ) UpperCamelCase = new_path.replace("""middle_block.2""" , """mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: UpperCamelCase = new_path.replace(replacement["""old"""] , replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: UpperCamelCase = old_checkpoint[path["""old"""]][:, :, 0] else: UpperCamelCase = old_checkpoint[path["""old"""]] def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = {} UpperCamelCase = checkpoint["""time_embed.0.weight"""] UpperCamelCase = checkpoint["""time_embed.0.bias"""] UpperCamelCase = checkpoint["""time_embed.2.weight"""] UpperCamelCase = checkpoint["""time_embed.2.bias"""] UpperCamelCase = checkpoint["""input_blocks.0.0.weight"""] UpperCamelCase = checkpoint["""input_blocks.0.0.bias"""] UpperCamelCase = checkpoint["""out.0.weight"""] UpperCamelCase = checkpoint["""out.0.bias"""] UpperCamelCase = checkpoint["""out.2.weight"""] UpperCamelCase = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"input_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the middle blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"middle_block.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the output blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"output_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } for i in range(1 , __UpperCamelCase ): UpperCamelCase = (i - 1) // (config["""num_res_blocks"""] + 1) UpperCamelCase = (i - 1) % (config["""num_res_blocks"""] + 1) UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.0" in key] UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.1" in key] if F"input_blocks.{i}.0.op.weight" in checkpoint: UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.weight" ] UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.bias" ] continue UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"input_blocks.{i}.0", """new""": F"down_blocks.{block_id}.resnets.{layer_in_block_id}"} UpperCamelCase = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path, resnet_op] , config=__UpperCamelCase ) if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"input_blocks.{i}.1", """new""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"input_blocks.{i}.1.qkv.bias": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"input_blocks.{i}.1.qkv.weight": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase , ) UpperCamelCase = middle_blocks[0] UpperCamelCase = middle_blocks[1] UpperCamelCase = middle_blocks[2] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase ) for i in range(__UpperCamelCase ): UpperCamelCase = i // (config["""num_res_blocks"""] + 1) UpperCamelCase = i % (config["""num_res_blocks"""] + 1) UpperCamelCase = [shave_segments(__UpperCamelCase , 2 ) for name in output_blocks[i]] UpperCamelCase = {} for layer in output_block_layers: UpperCamelCase ,UpperCamelCase = layer.split(""".""" )[0], shave_segments(__UpperCamelCase , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__UpperCamelCase ) else: UpperCamelCase = [layer_name] if len(__UpperCamelCase ) > 1: UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.0" in key] UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.1" in key] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"output_blocks.{i}.0", """new""": F"up_blocks.{block_id}.resnets.{layer_in_block_id}"} assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , config=__UpperCamelCase ) if ["conv.weight", "conv.bias"] in output_block_list.values(): UpperCamelCase = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.weight" ] UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.bias" ] # Clear attentions as they have been attributed above. if len(__UpperCamelCase ) == 2: UpperCamelCase = [] if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"output_blocks.{i}.1", """new""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"output_blocks.{i}.1.qkv.bias": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"output_blocks.{i}.1.qkv.weight": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None , config=__UpperCamelCase , ) else: UpperCamelCase = renew_resnet_paths(__UpperCamelCase , n_shave_prefix_segments=1 ) for path in resnet_0_paths: UpperCamelCase = """.""".join(["""output_blocks""", str(__UpperCamelCase ), path["""old"""]] ) UpperCamelCase = """.""".join(["""up_blocks""", str(__UpperCamelCase ), """resnets""", str(__UpperCamelCase ), path["""new"""]] ) UpperCamelCase = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = torch.load(args.checkpoint_path) with open(args.config_file) as f: SCREAMING_SNAKE_CASE__ = json.loads(f.read()) SCREAMING_SNAKE_CASE__ = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] SCREAMING_SNAKE_CASE__ = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: SCREAMING_SNAKE_CASE__ = DDPMScheduler.from_config('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = VQModel.from_pretrained('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
35
0
def lowercase__ ( __UpperCamelCase )-> Tuple: if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise TypeError("""Input value must be an 'int' type""" ) UpperCamelCase = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
720
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase = 0 # if input_string is "aba" than new_input_string become "a|b|a" UpperCamelCase = '''''' UpperCamelCase = '''''' # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(__UpperCamelCase ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring UpperCamelCase = 0, 0 # length[i] shows the length of palindromic substring with center i UpperCamelCase = [1 for i in range(len(__UpperCamelCase ) )] # for each character in new_string find corresponding palindromic string UpperCamelCase = 0 for j in range(len(__UpperCamelCase ) ): UpperCamelCase = 1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(__UpperCamelCase ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 UpperCamelCase = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: UpperCamelCase = j - k + 1 # noqa: E741 UpperCamelCase = j + k - 1 # update max_length and start position if max_length < length[j]: UpperCamelCase = length[j] UpperCamelCase = j # create that string UpperCamelCase = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
721
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration SCREAMING_SNAKE_CASE__ = 'facebook/wmt19-en-de' SCREAMING_SNAKE_CASE__ = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model SCREAMING_SNAKE_CASE__ = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) SCREAMING_SNAKE_CASE__ = FSMTForConditionalGeneration(config) print(f'num of params {tiny_model.num_parameters()}') # Test SCREAMING_SNAKE_CASE__ = tokenizer(['Making tiny model'], return_tensors='pt') SCREAMING_SNAKE_CASE__ = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save SCREAMING_SNAKE_CASE__ = 'tiny-wmt19-en-de' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f'Generated {mname_tiny}') # Upload # transformers-cli upload tiny-wmt19-en-de
35
0
'''simple docstring''' import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> List[str]: # Initialise PyTorch model UpperCamelCase = MobileBertConfig.from_json_file(_lowerCAmelCase ) print(F"Building PyTorch model from configuration: {config}" ) UpperCamelCase = MobileBertForPreTraining(_lowerCAmelCase ) # Load weights from tf checkpoint UpperCamelCase = load_tf_weights_in_mobilebert(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _lowerCAmelCase ) if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--mobilebert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained MobileBERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __a = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
700
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) SCREAMING_SNAKE_CASE__ = CLIPImageProcessor() SCREAMING_SNAKE_CASE__ = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') SCREAMING_SNAKE_CASE__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
35
0
'''simple docstring''' import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class a_ ( lowerCamelCase__ ): def A__ ( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" with open(__lowerCamelCase , encoding="""utf-8""" ) as input_file: UpperCamelCase = re.compile(R"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) UpperCamelCase = input_file.read() UpperCamelCase = regexp.search(__lowerCamelCase ) return match def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" with open(__lowerCamelCase , encoding="""utf-8""" ) as input_file: UpperCamelCase = re.compile(R"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) UpperCamelCase = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` UpperCamelCase = regexp.finditer(__lowerCamelCase ) UpperCamelCase = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = Path("""./datasets""" ) UpperCamelCase = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(__lowerCamelCase ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = Path("""./datasets""" ) UpperCamelCase = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(__lowerCamelCase ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
701
'''simple docstring''' from __future__ import annotations from typing import Any class a_ : def __init__( self , _SCREAMING_SNAKE_CASE = 6 ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None self.create_linked_list(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = current_node UpperCamelCase = current_node for _ in range(1 , _SCREAMING_SNAKE_CASE ): UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = previous_node UpperCamelCase = current_node UpperCamelCase = self.front UpperCamelCase = previous_node def A__ ( self ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCamelCase = self.rear.next if self.rear: UpperCamelCase = data def A__ ( self ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCamelCase = self.front.data UpperCamelCase = None return data UpperCamelCase = self.front UpperCamelCase = old_front.next UpperCamelCase = old_front.data UpperCamelCase = None return data def A__ ( self ) -> None: """simple docstring""" if self.is_empty(): raise Exception("""Empty Queue""" ) def A__ ( self ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class a_ : def __init__( self ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { "configuration_gpt_bigcode": ["GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTBigCodeConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ "GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTBigCodeForSequenceClassification", "GPTBigCodeForTokenClassification", "GPTBigCodeForCausalLM", "GPTBigCodeModel", "GPTBigCodePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
702
'''simple docstring''' import fire from utils import calculate_rouge, save_json def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , **__UpperCamelCase )-> int: UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()] UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()][: len(__UpperCamelCase )] UpperCamelCase = calculate_rouge(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) if save_path is not None: save_json(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
35
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = b.T UpperCamelCase = np.sum(np.square(__SCREAMING_SNAKE_CASE ) , axis=1 ) UpperCamelCase = np.sum(np.square(__SCREAMING_SNAKE_CASE ) , axis=0 ) UpperCamelCase = np.matmul(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) UpperCamelCase = aa[:, None] - 2 * ab + ba[None, :] return d def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Tuple: UpperCamelCase = x.reshape(-1 , 3 ) UpperCamelCase = squared_euclidean_distance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return np.argmin(__SCREAMING_SNAKE_CASE , axis=1 ) class a_ ( snake_case__ ): lowercase = ["""pixel_values"""] def __init__( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" super().__init__(**lowercase_ ) UpperCamelCase = size if size is not None else {"height": 256, "width": 256} UpperCamelCase = get_size_dict(lowercase_ ) UpperCamelCase = np.array(lowercase_ ) if clusters is not None else None UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = resample UpperCamelCase = do_normalize UpperCamelCase = do_color_quantize def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" UpperCamelCase = get_size_dict(lowercase_ ) if "height" not in size or "width" not in size: raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}" ) return resize( lowercase_ , size=(size["""height"""], size["""width"""]) , resample=lowercase_ , data_format=lowercase_ , **lowercase_ ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , ) -> Dict: """simple docstring""" UpperCamelCase = rescale(image=lowercase_ , scale=1 / 1_2_7.5 , data_format=lowercase_ ) UpperCamelCase = image - 1 return image def A__ ( self , _SCREAMING_SNAKE_CASE , _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 = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" UpperCamelCase = do_resize if do_resize is not None else self.do_resize UpperCamelCase = size if size is not None else self.size UpperCamelCase = get_size_dict(lowercase_ ) UpperCamelCase = resample if resample is not None else self.resample UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCamelCase = clusters if clusters is not None else self.clusters UpperCamelCase = np.array(lowercase_ ) UpperCamelCase = make_list_of_images(lowercase_ ) if not valid_images(lowercase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_color_quantize and clusters is None: raise ValueError("""Clusters must be specified if do_color_quantize is True.""" ) # All transformations expect numpy arrays. UpperCamelCase = [to_numpy_array(lowercase_ ) for image in images] if do_resize: UpperCamelCase = [self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_ ) for image in images] if do_normalize: UpperCamelCase = [self.normalize(image=lowercase_ ) for image in images] if do_color_quantize: UpperCamelCase = [to_channel_dimension_format(lowercase_ , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCamelCase = np.array(lowercase_ ) UpperCamelCase = color_quantize(lowercase_ , lowercase_ ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCamelCase = images.shape[0] UpperCamelCase = images.reshape(lowercase_ , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCamelCase = list(lowercase_ ) else: UpperCamelCase = [to_channel_dimension_format(lowercase_ , lowercase_ ) for image in images] UpperCamelCase = {"input_ids": images} return BatchFeature(data=lowercase_ , tensor_type=lowercase_ )
703
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> tuple[float, list[float]]: UpperCamelCase = list(range(len(__UpperCamelCase ) ) ) UpperCamelCase = [v / w for v, w in zip(__UpperCamelCase , __UpperCamelCase )] index.sort(key=lambda __UpperCamelCase : ratio[i] , reverse=__UpperCamelCase ) UpperCamelCase = 0 UpperCamelCase = [0] * len(__UpperCamelCase ) for i in index: if weight[i] <= capacity: UpperCamelCase = 1 max_value += value[i] capacity -= weight[i] else: UpperCamelCase = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename SCREAMING_SNAKE_CASE__ = "http://www.mocksite.com/file1.txt" SCREAMING_SNAKE_CASE__ = "\"text\": [\"foo\", \"foo\"]" SCREAMING_SNAKE_CASE__ = "6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8" class a_ : lowercase = 2_00 lowercase = {'''Content-Length''': '''100'''} lowercase = {} def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return [bytes(A_ , """utf-8""" )] def lowercase__ ( *__UpperCamelCase , **__UpperCamelCase )-> Dict: return MockResponse() @pytest.mark.parametrize("""urls_type""" , [str, list, dict] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Any: import requests monkeypatch.setattr(__UpperCamelCase , """request""" , __UpperCamelCase ) UpperCamelCase = URL if issubclass(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = url elif issubclass(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = [url] elif issubclass(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = {"""train""": url} UpperCamelCase = """dummy""" UpperCamelCase = """downloads""" UpperCamelCase = tmp_path UpperCamelCase = DownloadConfig( cache_dir=os.path.join(__UpperCamelCase , __UpperCamelCase ) , use_etag=__UpperCamelCase , ) UpperCamelCase = DownloadManager(dataset_name=__UpperCamelCase , download_config=__UpperCamelCase ) UpperCamelCase = dl_manager.download(__UpperCamelCase ) UpperCamelCase = urls for downloaded_paths in [downloaded_paths]: if isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = [downloaded_paths] UpperCamelCase = [urls] elif isinstance(__UpperCamelCase , __UpperCamelCase ): assert "train" in downloaded_paths.keys() UpperCamelCase = downloaded_paths.values() UpperCamelCase = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(__UpperCamelCase , __UpperCamelCase ): assert downloaded_path == dl_manager.downloaded_paths[input_url] UpperCamelCase = Path(__UpperCamelCase ) UpperCamelCase = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() UpperCamelCase = downloaded_path.read_text() assert content == CONTENT UpperCamelCase = downloaded_path.with_suffix(""".json""" ) assert metadata_downloaded_path.exists() UpperCamelCase = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize("""paths_type""" , [str, list, dict] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Optional[Any]: UpperCamelCase = str(__UpperCamelCase ) if issubclass(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = filename elif issubclass(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = [filename] elif issubclass(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = {"""train""": filename} UpperCamelCase = """dummy""" UpperCamelCase = xz_file.parent UpperCamelCase = """extracted""" UpperCamelCase = DownloadConfig( cache_dir=__UpperCamelCase , use_etag=__UpperCamelCase , ) UpperCamelCase = DownloadManager(dataset_name=__UpperCamelCase , download_config=__UpperCamelCase ) UpperCamelCase = dl_manager.extract(__UpperCamelCase ) UpperCamelCase = paths for extracted_paths in [extracted_paths]: if isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = [extracted_paths] UpperCamelCase = [paths] elif isinstance(__UpperCamelCase , __UpperCamelCase ): assert "train" in extracted_paths.keys() UpperCamelCase = extracted_paths.values() UpperCamelCase = paths.values() assert extracted_paths for extracted_path, input_path in zip(__UpperCamelCase , __UpperCamelCase ): assert extracted_path == dl_manager.extracted_paths[input_path] UpperCamelCase = Path(__UpperCamelCase ) UpperCamelCase = extracted_path.parts assert parts[-1] == hash_url_to_filename(__UpperCamelCase , etag=__UpperCamelCase ) assert parts[-2] == extracted_subdir assert extracted_path.exists() UpperCamelCase = extracted_path.read_text() UpperCamelCase = text_file.read_text() assert extracted_file_content == expected_file_content def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> int: assert path.endswith(""".jsonl""" ) for num_items, line in enumerate(__UpperCamelCase , start=1 ): UpperCamelCase = json.loads(line.decode("""utf-8""" ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize("""archive_jsonl""" , ["""tar_jsonl_path""", """zip_jsonl_path"""] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = request.getfixturevalue(__UpperCamelCase ) UpperCamelCase = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(__UpperCamelCase ) , start=1 ): _test_jsonl(__UpperCamelCase , __UpperCamelCase ) assert num_jsonl == 2 @pytest.mark.parametrize("""archive_nested_jsonl""" , ["""tar_nested_jsonl_path""", """zip_nested_jsonl_path"""] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Union[str, Any]: UpperCamelCase = request.getfixturevalue(__UpperCamelCase ) UpperCamelCase = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(__UpperCamelCase ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(__UpperCamelCase ) , start=1 ): _test_jsonl(__UpperCamelCase , __UpperCamelCase ) assert num_tar == 1 assert num_jsonl == 2 def lowercase__ ( __UpperCamelCase )-> Any: UpperCamelCase = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(__UpperCamelCase ) , start=1 ): assert os.path.basename(__UpperCamelCase ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
704
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a_ ( lowerCamelCase ): lowercase = """deformable_detr""" lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # deformable attributes UpperCamelCase = num_feature_levels UpperCamelCase = encoder_n_points UpperCamelCase = decoder_n_points UpperCamelCase = two_stage UpperCamelCase = two_stage_num_proposals UpperCamelCase = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient UpperCamelCase = focal_alpha UpperCamelCase = disable_custom_kernels super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A__ ( self ) -> int: """simple docstring""" return self.d_model def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output
35
0
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[1, 1, 2, 1] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = num_channels UpperCamelCase = embeddings_size UpperCamelCase = hidden_sizes UpperCamelCase = depths UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = hidden_act UpperCamelCase = num_labels UpperCamelCase = scope UpperCamelCase = len(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels def A__ ( self ) -> Dict: """simple docstring""" return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" UpperCamelCase = TFResNetModel(config=_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = TFResNetForImageClassification(_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase = config_and_inputs UpperCamelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class a_ ( __lowercase , __lowercase , unittest.TestCase ): lowercase = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () lowercase = ( {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification} if is_tf_available() else {} ) lowercase = False lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = TFResNetModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A__ ( self ) -> List[str]: """simple docstring""" return @unittest.skip(reason="""ResNet does not use inputs_embeds""" ) def A__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="""ResNet does not support input and output embeddings""" ) def A__ ( self ) -> Tuple: """simple docstring""" pass def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase = self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: UpperCamelCase = layer_type UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def A__ ( self ) -> Tuple: """simple docstring""" for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = TFResNetModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowercase__ ( )-> Optional[int]: UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class a_ ( unittest.TestCase ): @cached_property def A__ ( self ) -> str: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) # forward pass UpperCamelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits UpperCamelCase = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase = tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
705
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowercase__ ( __UpperCamelCase )-> Any: UpperCamelCase = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase ,UpperCamelCase = emb.weight.shape UpperCamelCase = nn.Linear(__UpperCamelCase , __UpperCamelCase , bias=__UpperCamelCase ) UpperCamelCase = emb.weight.data return lin_layer def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase = torch.load(__UpperCamelCase , map_location="""cpu""" ) UpperCamelCase = mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""] UpperCamelCase = mam_aaa["""model"""] remove_ignore_keys_(__UpperCamelCase ) UpperCamelCase = state_dict["""encoder.embed_tokens.weight"""].shape[0] UpperCamelCase = MaMaaaConfig( vocab_size=__UpperCamelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , ) UpperCamelCase = state_dict["""decoder.embed_tokens.weight"""] UpperCamelCase = MaMaaaForConditionalGeneration(__UpperCamelCase ) model.model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) UpperCamelCase = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
35
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json", "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json", "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json", "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json", "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json", "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json", "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json", "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json", "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json", "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json", } class a_ ( lowerCamelCase ): lowercase = """rwkv""" lowercase = {"""max_position_embeddings""": """context_length"""} def __init__( self , _SCREAMING_SNAKE_CASE=50277 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> Optional[int]: """simple docstring""" UpperCamelCase = vocab_size UpperCamelCase = context_length UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = attention_hidden_size if attention_hidden_size is not None else hidden_size UpperCamelCase = intermediate_size if intermediate_size is not None else 4 * hidden_size UpperCamelCase = layer_norm_epsilon UpperCamelCase = rescale_every UpperCamelCase = use_cache UpperCamelCase = bos_token_id UpperCamelCase = eos_token_id super().__init__( tie_word_embeddings=__UpperCamelCase , bos_token_id=__UpperCamelCase , eos_token_id=__UpperCamelCase , **__UpperCamelCase )
706
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class a_ ( lowerCamelCase ): def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """tf_padding""" ) ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """depth_multiplier""" ) ) class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE="relu6" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=None , ) -> List[str]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = depth_multiplier UpperCamelCase = min_depth UpperCamelCase = tf_padding UpperCamelCase = int(last_hidden_size * depth_multiplier ) UpperCamelCase = output_stride UpperCamelCase = hidden_act UpperCamelCase = classifier_dropout_prob UpperCamelCase = use_labels UpperCamelCase = is_training UpperCamelCase = num_labels UpperCamelCase = initializer_range UpperCamelCase = scope def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels, pixel_labels def A__ ( self ) -> Optional[Any]: """simple docstring""" return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = MobileNetVaForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowercase = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModelTester(self ) UpperCamelCase = MobileNetVaConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not output attentions""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = 26 self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def A__ ( self ) -> Dict: """simple docstring""" for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = MobileNetVaModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowercase__ ( )-> Optional[Any]: UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def A__ ( self ) -> Dict: """simple docstring""" return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224""" ) if is_vision_available() else None ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224""" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits UpperCamelCase = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
35
0
'''simple docstring''' from __future__ import annotations import os from collections.abc import Mapping SCREAMING_SNAKE_CASE__ = tuple[int, int] class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" UpperCamelCase = vertices UpperCamelCase = { (min(_SCREAMING_SNAKE_CASE ), max(_SCREAMING_SNAKE_CASE )): weight for edge, weight in edges.items() } def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) UpperCamelCase = weight def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = Graph({min(self.vertices )} , {} ) UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 while len(subgraph.vertices ) < len(self.vertices ): UpperCamelCase = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: UpperCamelCase = edge UpperCamelCase = weight subgraph.add_edge(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return subgraph def lowercase__ ( __UpperCamelCase = "p107_network.txt" )-> int: UpperCamelCase = os.path.abspath(os.path.dirname(__UpperCamelCase ) ) UpperCamelCase = os.path.join(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase = {} UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 with open(__UpperCamelCase ) as f: UpperCamelCase = f.read().strip().split("""\n""" ) UpperCamelCase = [line.split(""",""" ) for line in data] for edgea in range(1 , len(__UpperCamelCase ) ): for edgea in range(__UpperCamelCase ): if adjaceny_matrix[edgea][edgea] != "-": UpperCamelCase = int(adjaceny_matrix[edgea][edgea] ) UpperCamelCase = Graph(set(range(len(__UpperCamelCase ) ) ) , __UpperCamelCase ) UpperCamelCase = graph.prims_algorithm() UpperCamelCase = sum(graph.edges.values() ) UpperCamelCase = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(f'{solution() = }')
707
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-1' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-2' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-3' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-4' class a_ ( lowerCamelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , ) -> Any: """simple docstring""" super()._init_() UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline( vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , requires_safety_checker=_SCREAMING_SNAKE_CASE , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def A__ ( self ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , _SCREAMING_SNAKE_CASE ) for k in self.config.keys() if not k.startswith("""_""" )} def A__ ( self , _SCREAMING_SNAKE_CASE = "auto" ) -> Optional[Any]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" self.enable_attention_slicing(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" UpperCamelCase = """cuda""" if torch.cuda.is_available() else """cpu""" self.to(_SCREAMING_SNAKE_CASE ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
35
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class a_ ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 255 , _SCREAMING_SNAKE_CASE=True , ) -> List[str]: """simple docstring""" UpperCamelCase = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = min_resolution UpperCamelCase = max_resolution UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = do_normalize UpperCamelCase = image_mean UpperCamelCase = image_std UpperCamelCase = do_rescale UpperCamelCase = rescale_factor UpperCamelCase = do_pad def A__ ( self ) -> str: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: """simple docstring""" if not batched: UpperCamelCase = image_inputs[0] if isinstance(UpperCamelCase__ , Image.Image ): UpperCamelCase = image.size else: UpperCamelCase = image.shape[1], image.shape[2] if w < h: UpperCamelCase = int(self.size["""shortest_edge"""] * h / w ) UpperCamelCase = self.size['shortest_edge'] elif w > h: UpperCamelCase = self.size['shortest_edge'] UpperCamelCase = int(self.size["""shortest_edge"""] * w / h ) else: UpperCamelCase = self.size['shortest_edge'] UpperCamelCase = self.size['shortest_edge'] else: UpperCamelCase = [] for image in image_inputs: UpperCamelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCamelCase = max(UpperCamelCase__ , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] UpperCamelCase = max(UpperCamelCase__ , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a_ ( __A , unittest.TestCase ): lowercase = YolosImageProcessor if is_vision_available() else None def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = YolosImageProcessingTester(self ) @property def A__ ( self ) -> Dict: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCamelCase__ , """image_mean""" ) ) self.assertTrue(hasattr(UpperCamelCase__ , """image_std""" ) ) self.assertTrue(hasattr(UpperCamelCase__ , """do_normalize""" ) ) self.assertTrue(hasattr(UpperCamelCase__ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCamelCase__ , """size""" ) ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 1333} ) self.assertEqual(image_processor.do_pad , UpperCamelCase__ ) UpperCamelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=UpperCamelCase__ ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42, """longest_edge""": 84} ) self.assertEqual(image_processor.do_pad , UpperCamelCase__ ) def A__ ( self ) -> str: """simple docstring""" pass def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase__ , Image.Image ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(UpperCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase = self.image_processor_tester.get_expected_values(UpperCamelCase__ , batched=UpperCamelCase__ ) UpperCamelCase = image_processing(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ , numpify=UpperCamelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase__ , np.ndarray ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(UpperCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase = image_processing(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(UpperCamelCase__ , batched=UpperCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ , torchify=UpperCamelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase__ , torch.Tensor ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(UpperCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase = image_processing(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(UpperCamelCase__ , batched=UpperCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) UpperCamelCase = self.image_processing_class(do_resize=UpperCamelCase__ , do_normalize=UpperCamelCase__ , do_rescale=UpperCamelCase__ ) # create random PyTorch tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCamelCase__ , torchify=UpperCamelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCamelCase__ , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors UpperCamelCase = image_processing_a.pad(UpperCamelCase__ , return_tensors="""pt""" ) UpperCamelCase = image_processing_a(UpperCamelCase__ , return_tensors="""pt""" ) self.assertTrue( torch.allclose(encoded_images_with_method["""pixel_values"""] , encoded_images["""pixel_values"""] , atol=1e-4 ) ) @slow def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: UpperCamelCase = json.loads(f.read() ) UpperCamelCase = {'image_id': 39769, 'annotations': target} # encode them UpperCamelCase = YolosImageProcessor.from_pretrained("""hustvl/yolos-small""" ) UpperCamelCase = image_processing(images=UpperCamelCase__ , annotations=UpperCamelCase__ , return_tensors="""pt""" ) # verify pixel values UpperCamelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , UpperCamelCase__ ) UpperCamelCase = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , UpperCamelCase__ , atol=1e-4 ) ) # verify area UpperCamelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , UpperCamelCase__ ) ) # verify boxes UpperCamelCase = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , UpperCamelCase__ ) UpperCamelCase = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , UpperCamelCase__ , atol=1e-3 ) ) # verify image_id UpperCamelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , UpperCamelCase__ ) ) # verify is_crowd UpperCamelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , UpperCamelCase__ ) ) # verify class_labels UpperCamelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , UpperCamelCase__ ) ) # verify orig_size UpperCamelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , UpperCamelCase__ ) ) # verify size UpperCamelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , UpperCamelCase__ ) ) @slow def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: UpperCamelCase = json.loads(f.read() ) UpperCamelCase = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} UpperCamelCase = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them UpperCamelCase = YolosImageProcessor(format="""coco_panoptic""" ) UpperCamelCase = image_processing(images=UpperCamelCase__ , annotations=UpperCamelCase__ , masks_path=UpperCamelCase__ , return_tensors="""pt""" ) # verify pixel values UpperCamelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , UpperCamelCase__ ) UpperCamelCase = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , UpperCamelCase__ , atol=1e-4 ) ) # verify area UpperCamelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , UpperCamelCase__ ) ) # verify boxes UpperCamelCase = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , UpperCamelCase__ ) UpperCamelCase = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , UpperCamelCase__ , atol=1e-3 ) ) # verify image_id UpperCamelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , UpperCamelCase__ ) ) # verify is_crowd UpperCamelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , UpperCamelCase__ ) ) # verify class_labels UpperCamelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , UpperCamelCase__ ) ) # verify masks UpperCamelCase = 822873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , UpperCamelCase__ ) # verify orig_size UpperCamelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , UpperCamelCase__ ) ) # verify size UpperCamelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , UpperCamelCase__ ) )
708
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE__ = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=True , __UpperCamelCase="pt" )-> Tuple: UpperCamelCase = {"""add_prefix_space""": True} if isinstance(__UpperCamelCase , __UpperCamelCase ) and not line.startswith(""" """ ) else {} UpperCamelCase = padding_side return tokenizer( [line] , max_length=__UpperCamelCase , padding="""max_length""" if pad_to_max_length else None , truncation=__UpperCamelCase , return_tensors=__UpperCamelCase , add_special_tokens=__UpperCamelCase , **__UpperCamelCase , ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , )-> str: UpperCamelCase = input_ids.ne(__UpperCamelCase ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class a_ ( a__ ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="train" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="" , ) -> str: """simple docstring""" super().__init__() UpperCamelCase = Path(lowerCamelCase_ ).joinpath(type_path + """.source""" ) UpperCamelCase = Path(lowerCamelCase_ ).joinpath(type_path + """.target""" ) UpperCamelCase = self.get_char_lens(self.src_file ) UpperCamelCase = max_source_length UpperCamelCase = max_target_length assert min(self.src_lens ) > 0, F"found empty line in {self.src_file}" UpperCamelCase = tokenizer UpperCamelCase = prefix if n_obs is not None: UpperCamelCase = self.src_lens[:n_obs] UpperCamelCase = src_lang UpperCamelCase = tgt_lang def __len__( self ) -> Tuple: """simple docstring""" return len(self.src_lens ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Dict[str, torch.Tensor]: """simple docstring""" UpperCamelCase = index + 1 # linecache starts at 1 UpperCamelCase = self.prefix + linecache.getline(str(self.src_file ) , lowerCamelCase_ ).rstrip("""\n""" ) UpperCamelCase = linecache.getline(str(self.tgt_file ) , lowerCamelCase_ ).rstrip("""\n""" ) assert source_line, F"empty source line for index {index}" assert tgt_line, F"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer , lowerCamelCase_ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right UpperCamelCase = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer ) UpperCamelCase = self.tokenizer.generator if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer UpperCamelCase = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_source_length , """right""" ) UpperCamelCase = encode_line(lowerCamelCase_ , lowerCamelCase_ , self.max_target_length , """right""" ) UpperCamelCase = source_inputs["""input_ids"""].squeeze() UpperCamelCase = target_inputs["""input_ids"""].squeeze() UpperCamelCase = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return [len(lowerCamelCase_ ) for x in Path(lowerCamelCase_ ).open().readlines()] def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict[str, torch.Tensor]: """simple docstring""" UpperCamelCase = torch.stack([x["""input_ids"""] for x in batch] ) UpperCamelCase = torch.stack([x["""attention_mask"""] for x in batch] ) UpperCamelCase = torch.stack([x["""decoder_input_ids"""] for x in batch] ) UpperCamelCase = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) UpperCamelCase = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , lowerCamelCase_ ) else self.tokenizer.pad_token_id ) UpperCamelCase = trim_batch(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase ,UpperCamelCase = trim_batch(lowerCamelCase_ , lowerCamelCase_ , attention_mask=lowerCamelCase_ ) UpperCamelCase = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch SCREAMING_SNAKE_CASE__ = getLogger(__name__) def lowercase__ ( __UpperCamelCase )-> Tuple: return list(itertools.chain.from_iterable(__UpperCamelCase ) ) def lowercase__ ( __UpperCamelCase )-> None: UpperCamelCase = get_git_info() save_json(__UpperCamelCase , os.path.join(__UpperCamelCase , """git_log.json""" ) ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=4 , **__UpperCamelCase )-> Optional[int]: with open(__UpperCamelCase , """w""" ) as f: json.dump(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase , **__UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> Optional[int]: with open(__UpperCamelCase ) as f: return json.load(__UpperCamelCase ) def lowercase__ ( )-> str: UpperCamelCase = git.Repo(search_parent_directories=__UpperCamelCase ) UpperCamelCase = { """repo_id""": str(__UpperCamelCase ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List: return list(map(__UpperCamelCase , __UpperCamelCase ) ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: with open(__UpperCamelCase , """wb""" ) as f: return pickle.dump(__UpperCamelCase , __UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> int: def remove_articles(__UpperCamelCase ): return re.sub(R"""\b(a|an|the)\b""" , """ """ , __UpperCamelCase ) def white_space_fix(__UpperCamelCase ): return " ".join(text.split() ) def remove_punc(__UpperCamelCase ): UpperCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__UpperCamelCase ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__UpperCamelCase ) ) ) ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: UpperCamelCase = normalize_answer(__UpperCamelCase ).split() UpperCamelCase = normalize_answer(__UpperCamelCase ).split() UpperCamelCase = Counter(__UpperCamelCase ) & Counter(__UpperCamelCase ) UpperCamelCase = sum(common.values() ) if num_same == 0: return 0 UpperCamelCase = 1.0 * num_same / len(__UpperCamelCase ) UpperCamelCase = 1.0 * num_same / len(__UpperCamelCase ) UpperCamelCase = (2 * precision * recall) / (precision + recall) return fa def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: return normalize_answer(__UpperCamelCase ) == normalize_answer(__UpperCamelCase ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Dict: assert len(__UpperCamelCase ) == len(__UpperCamelCase ) UpperCamelCase = 0 for hypo, pred in zip(__UpperCamelCase , __UpperCamelCase ): em += exact_match_score(__UpperCamelCase , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: em /= len(__UpperCamelCase ) return {"em": em} def lowercase__ ( __UpperCamelCase )-> Union[str, Any]: return model_prefix.startswith("""rag""" ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Optional[Any]: UpperCamelCase = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead UpperCamelCase = """dropout_rate""" for p in extra_params: if getattr(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): if not hasattr(__UpperCamelCase , __UpperCamelCase ) and not hasattr(__UpperCamelCase , equivalent_param[p] ): logger.info("""config doesn\'t have a `{}` attribute""".format(__UpperCamelCase ) ) delattr(__UpperCamelCase , __UpperCamelCase ) continue UpperCamelCase = p if hasattr(__UpperCamelCase , __UpperCamelCase ) else equivalent_param[p] setattr(__UpperCamelCase , __UpperCamelCase , getattr(__UpperCamelCase , __UpperCamelCase ) ) delattr(__UpperCamelCase , __UpperCamelCase ) return hparams, config
709
'''simple docstring''' SCREAMING_SNAKE_CASE__ = 8.31_44_62 # Unit - J mol-1 K-1 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE__ = { 'configuration_m2m_100': ['M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP', 'M2M100Config', 'M2M100OnnxConfig'], 'tokenization_m2m_100': ['M2M100Tokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST', 'M2M100ForConditionalGeneration', 'M2M100Model', 'M2M100PreTrainedModel', ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
710
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__ = 1_6 SCREAMING_SNAKE_CASE__ = 3_2 def lowercase__ ( __UpperCamelCase , __UpperCamelCase = 16 )-> Dict: UpperCamelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__UpperCamelCase , max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__UpperCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase = 16 elif accelerator.mixed_precision != "no": UpperCamelCase = 8 else: UpperCamelCase = None return tokenizer.pad( __UpperCamelCase , padding="""longest""" , max_length=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. UpperCamelCase = DataLoader( tokenized_datasets["""train"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) UpperCamelCase = DataLoader( tokenized_datasets["""validation"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE__ = mocked_dataloaders # noqa: F811 def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List[Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __UpperCamelCase ) == "1": UpperCamelCase = 2 # New Code # UpperCamelCase = int(args.gradient_accumulation_steps ) UpperCamelCase = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__UpperCamelCase ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase = config["""lr"""] UpperCamelCase = int(config["""num_epochs"""] ) UpperCamelCase = int(config["""seed"""] ) UpperCamelCase = int(config["""batch_size"""] ) UpperCamelCase = evaluate.load("""glue""" , """mrpc""" ) set_seed(__UpperCamelCase ) UpperCamelCase ,UpperCamelCase = get_dataloaders(__UpperCamelCase , __UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase = AdamW(params=model.parameters() , lr=__UpperCamelCase ) # Instantiate scheduler UpperCamelCase = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase , num_warmup_steps=100 , num_training_steps=(len(__UpperCamelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = accelerator.prepare( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Now we train the model for epoch in range(__UpperCamelCase ): model.train() with LocalSGD( accelerator=__UpperCamelCase , model=__UpperCamelCase , local_sgd_steps=__UpperCamelCase , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__UpperCamelCase ): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = output.loss accelerator.backward(__UpperCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = outputs.logits.argmax(dim=-1 ) UpperCamelCase ,UpperCamelCase = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__UpperCamelCase , references=__UpperCamelCase , ) UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __UpperCamelCase ) def lowercase__ ( )-> List[Any]: UpperCamelCase = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__UpperCamelCase , default=__UpperCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__UpperCamelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument( """--local_sgd_steps""" , type=__UpperCamelCase , default=8 , help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) UpperCamelCase = parser.parse_args() UpperCamelCase = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
35
0
'''simple docstring''' import qiskit def lowercase__ ( __UpperCamelCase = 2 )-> qiskit.result.counts.Counts: UpperCamelCase = qubits # Using Aer's simulator UpperCamelCase = qiskit.Aer.get_backend("""aer_simulator""" ) # Creating a Quantum Circuit acting on the q register UpperCamelCase = qiskit.QuantumCircuit(__lowerCAmelCase , __lowerCAmelCase ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , __lowerCAmelCase ): # Adding CX (CNOT) gate circuit.cx(i - 1 , __lowerCAmelCase ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(__lowerCAmelCase ) ) , list(range(__lowerCAmelCase ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator UpperCamelCase = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1000 ) return job.result().get_counts(__lowerCAmelCase ) if __name__ == "__main__": print(f'Total count for various states are: {quantum_entanglement(3)}')
711
'''simple docstring''' import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> Any: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = embed_dim UpperCamelCase = depths 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 = patch_norm UpperCamelCase = layer_norm_eps UpperCamelCase = initializer_range UpperCamelCase = is_training UpperCamelCase = scope UpperCamelCase = use_labels UpperCamelCase = type_sequence_label_size UpperCamelCase = encoder_stride UpperCamelCase = out_features UpperCamelCase = out_indices def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = self.get_config() return config, pixel_values, labels def A__ ( self ) -> str: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) UpperCamelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = ["""stem"""] UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowercase = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {} lowercase = False lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with""" """ `nn.DataParallel`""" ) ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self ) -> Dict: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A__ ( self ) -> int: """simple docstring""" return def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip("""Swin does not use inputs_embeds""" ) def A__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip("""Swin does not support feedforward chunking""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" ) def A__ ( self ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = 3 UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> List[Any]: """simple docstring""" pass def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): UpperCamelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( """Tuple and dict output are not equal. Difference:""" F" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:" F" {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has" F" `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}." ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) @require_torch class a_ ( unittest.TestCase , lowerCamelCase ): lowercase = (MaskFormerSwinBackbone,) if is_torch_available() else () lowercase = MaskFormerSwinConfig def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = inputs_dict["""pixel_values"""].shape[0] for backbone_class in self.all_model_classes: UpperCamelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
35
0
'''simple docstring''' import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) def lowercase__ ( __UpperCamelCase )-> Optional[int]: UpperCamelCase = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError("""Quantized models are not supported.""" ) UpperCamelCase = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""" , a_ ) if matches: UpperCamelCase = float(matches[1] ) UpperCamelCase = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". UpperCamelCase = 1001 UpperCamelCase = '''imagenet-1k-id2label.json''' UpperCamelCase = '''huggingface/label-files''' UpperCamelCase = json.load(open(hf_hub_download(a_ , a_ , repo_type="""dataset""" ) , """r""" ) ) UpperCamelCase = {int(a_ ) + 1: v for k, v in idalabel.items()} UpperCamelCase = '''background''' UpperCamelCase = idalabel UpperCamelCase = {v: k for k, v in idalabel.items()} return config def lowercase__ ( )-> List[str]: UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCamelCase = Image.open(requests.get(a_ , stream=a_ ).raw ) return im @torch.no_grad() def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=False )-> List[Any]: UpperCamelCase = get_mobilenet_va_config(a_ ) # Load 🤗 model UpperCamelCase = MobileNetVaForImageClassification(a_ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(a_ , a_ , a_ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor UpperCamelCase = MobileNetVaImageProcessor( crop_size={"""width""": config.image_size, """height""": config.image_size} , size={"""shortest_edge""": config.image_size + 32} , ) UpperCamelCase = image_processor(images=prepare_img() , return_tensors="""pt""" ) UpperCamelCase = model(**a_ ) UpperCamelCase = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": UpperCamelCase = torch.tensor([-4.1_739, -1.1_233, 3.1_205] ) elif model_name == "mobilenet_v1_0.75_192": UpperCamelCase = torch.tensor([-3.9_440, -2.3_141, -0.3_333] ) else: UpperCamelCase = None if expected_logits is not None: assert torch.allclose(logits[0, :3] , a_ , atol=1E-4 ) Path(a_ ).mkdir(exist_ok=a_ ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(a_ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(a_ ) if push_to_hub: print("""Pushing to the hub...""" ) UpperCamelCase = '''google/''' + model_name image_processor.push_to_hub(a_ ) model.push_to_hub(a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
712
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand() def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand(args.accelerate_config_file ) class a_ ( lowerCamelCase ): @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = parser.add_parser("""env""" ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) download_parser.add_argument( """--accelerate-config_file""" , default=_SCREAMING_SNAKE_CASE , help="""The accelerate config file to use for the default values in the launching script.""" , ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def __init__( self , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = accelerate_config_file def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = """not installed""" if is_safetensors_available(): import safetensors UpperCamelCase = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors UpperCamelCase = F"{safetensors.__version__} but is ignored because of PyTorch version too old." UpperCamelCase = """not installed""" UpperCamelCase = UpperCamelCase = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file UpperCamelCase = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_SCREAMING_SNAKE_CASE ): UpperCamelCase = load_config_from_file(self._accelerate_config_file ).to_dict() UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else F"\t{accelerate_config}" ) UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_torch_available(): import torch UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_tf_available(): import tensorflow as tf UpperCamelCase = tf.__version__ try: # deprecated in v2.1 UpperCamelCase = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool UpperCamelCase = bool(tf.config.list_physical_devices("""GPU""" ) ) UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_flax_available(): import flax import jax import jaxlib UpperCamelCase = flax.__version__ UpperCamelCase = jax.__version__ UpperCamelCase = jaxlib.__version__ UpperCamelCase = jax.lib.xla_bridge.get_backend().platform UpperCamelCase = { """`transformers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Huggingface_hub version""": huggingface_hub.__version__, """Safetensors version""": F"{safetensors_version}", """Accelerate version""": F"{accelerate_version}", """Accelerate config""": F"{accelerate_config_str}", """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """Tensorflow version (GPU?)""": F"{tf_version} ({tf_cuda_available})", """Flax version (CPU?/GPU?/TPU?)""": F"{flax_version} ({jax_backend})", """Jax version""": F"{jax_version}", """JaxLib version""": F"{jaxlib_version}", """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(_SCREAMING_SNAKE_CASE ) ) return info @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
35
0
'''simple docstring''' # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> List[str]: UpperCamelCase = { """en""": """Machine learning is great, isn\'t it?""", """ru""": """Машинное обучение - это здорово, не так ли?""", """de""": """Maschinelles Lernen ist großartig, oder?""", } # BLUE scores as follows: # "pair": [fairseq, transformers] UpperCamelCase = { """ru-en""": ["""[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)""", """39.20"""], """en-ru""": ["""[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)""", """33.47"""], """en-de""": ["""[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)""", """42.83"""], """de-en""": ["""[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)""", """41.35"""], } UpperCamelCase = F"{src_lang}-{tgt_lang}" UpperCamelCase = F"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n" os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) UpperCamelCase = os.path.join(UpperCAmelCase__ , """README.md""" ) print(F"Generating {path}" ) with open(UpperCAmelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(UpperCAmelCase__ ) # make sure we are under the root of the project SCREAMING_SNAKE_CASE__ = Path(__file__).resolve().parent.parent.parent SCREAMING_SNAKE_CASE__ = repo_dir / 'model_cards' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model_name.split('-') SCREAMING_SNAKE_CASE__ = model_cards_dir / 'facebook' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
713
'''simple docstring''' from math import factorial def lowercase__ ( __UpperCamelCase = 20 )-> int: UpperCamelCase = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCamelCase = n // 2 return int(factorial(__UpperCamelCase ) / (factorial(__UpperCamelCase ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: SCREAMING_SNAKE_CASE__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
35
0
'''simple docstring''' from collections.abc import Generator def lowercase__ ( )-> Generator[int, None, None]: UpperCamelCase ,UpperCamelCase = 0, 1 while True: UpperCamelCase ,UpperCamelCase = b, a + b yield b def lowercase__ ( __UpperCamelCase = 1000 )-> int: UpperCamelCase = 1 UpperCamelCase = fibonacci_generator() while len(str(next(UpperCAmelCase__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
714
'''simple docstring''' from math import sqrt def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = 0 for i in range(1 , int(sqrt(__UpperCamelCase ) + 1 ) ): if n % i == 0 and i != sqrt(__UpperCamelCase ): total += i + n // i elif i == sqrt(__UpperCamelCase ): total += i return total - n def lowercase__ ( __UpperCamelCase = 10000 )-> int: UpperCamelCase = sum( i for i in range(1 , __UpperCamelCase ) if sum_of_divisors(sum_of_divisors(__UpperCamelCase ) ) == i and sum_of_divisors(__UpperCamelCase ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
35
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
715
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ = { """configuration_rag""": ["""RagConfig"""], """retrieval_rag""": ["""RagRetriever"""], """tokenization_rag""": ["""RagTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ """RagModel""", """RagPreTrainedModel""", """RagSequenceForGeneration""", """RagTokenForGeneration""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ """TFRagModel""", """TFRagPreTrainedModel""", """TFRagSequenceForGeneration""", """TFRagTokenForGeneration""", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
716
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> str: if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase = """""" while len(__UpperCamelCase ) % 3 != 0: UpperCamelCase = """0""" + bin_string UpperCamelCase = [ bin_string[index : index + 3] for index in range(len(__UpperCamelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase = 0 for index, val in enumerate(__UpperCamelCase ): oct_val += int(2 ** (2 - index) * int(__UpperCamelCase ) ) oct_string += str(__UpperCamelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json", "allenai/longformer-large-4096": "https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json", "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json" ), } class a_ ( __lowerCAmelCase ): '''simple docstring''' lowercase = "longformer" def __init__( self , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = 30522 , _SCREAMING_SNAKE_CASE = 768 , _SCREAMING_SNAKE_CASE = 12 , _SCREAMING_SNAKE_CASE = 12 , _SCREAMING_SNAKE_CASE = 3072 , _SCREAMING_SNAKE_CASE = "gelu" , _SCREAMING_SNAKE_CASE = 0.1 , _SCREAMING_SNAKE_CASE = 0.1 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 2 , _SCREAMING_SNAKE_CASE = 0.0_2 , _SCREAMING_SNAKE_CASE = 1e-12 , _SCREAMING_SNAKE_CASE = False , **_SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(pad_token_id=lowerCamelCase__ , **lowerCamelCase__ ) UpperCamelCase = attention_window UpperCamelCase = sep_token_id UpperCamelCase = bos_token_id UpperCamelCase = eos_token_id UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = onnx_export class a_ ( __lowerCAmelCase ): '''simple docstring''' def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "default" , _SCREAMING_SNAKE_CASE = None ) -> List[str]: """simple docstring""" super().__init__(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase = True @property def A__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": UpperCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""global_attention_mask""", dynamic_axis), ] ) @property def A__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" UpperCamelCase = super().outputs if self.task == "default": UpperCamelCase = {0: '''batch'''} return outputs @property def A__ ( self ) -> float: """simple docstring""" return 1e-4 @property def A__ ( self ) -> int: """simple docstring""" return max(super().default_onnx_opset , 14 ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase = super().generate_dummy_inputs( preprocessor=lowerCamelCase__ , batch_size=lowerCamelCase__ , seq_length=lowerCamelCase__ , is_pair=lowerCamelCase__ , framework=lowerCamelCase__ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly UpperCamelCase = torch.zeros_like(inputs["""input_ids"""] ) # make every second token global UpperCamelCase = 1 return inputs
717
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowercase__ ( __UpperCamelCase=None )-> Union[str, Any]: if subparsers is not None: UpperCamelCase = subparsers.add_parser("""env""" ) else: UpperCamelCase = argparse.ArgumentParser("""Accelerate env command""" ) parser.add_argument( """--config_file""" , default=__UpperCamelCase , help="""The config file to use for the default values in the launching script.""" ) if subparsers is not None: parser.set_defaults(func=__UpperCamelCase ) return parser def lowercase__ ( __UpperCamelCase )-> List[str]: UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = is_xpu_available() UpperCamelCase = is_npu_available() UpperCamelCase = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(__UpperCamelCase ): UpperCamelCase = load_config_from_file(args.config_file ).to_dict() UpperCamelCase = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """PyTorch XPU available""": str(__UpperCamelCase ), """PyTorch NPU available""": str(__UpperCamelCase ), """System RAM""": F"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", } if pt_cuda_available: UpperCamelCase = torch.cuda.get_device_name() print("""\nCopy-and-paste the text below in your GitHub issue\n""" ) print("""\n""".join([F"- {prop}: {val}" for prop, val in info.items()] ) ) print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" ) UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else F"\t{accelerate_config}" ) print(__UpperCamelCase ) UpperCamelCase = accelerate_config return info def lowercase__ ( )-> int: UpperCamelCase = env_command_parser() UpperCamelCase = parser.parse_args() env_command(__UpperCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
35
0
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class a_ ( UpperCamelCase_ ): def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = SMALL_MODEL_IDENTIFIER UpperCamelCase = '''pt''' UpperCamelCase = '''tf''' def A__ ( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = TFAutoModel.from_pretrained(self.test_model , from_pt=_SCREAMING_SNAKE_CASE ) model_tf.save_pretrained(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = '''mock_framework''' # Framework provided - return whatever the user provides UpperCamelCase = FeaturesManager.determine_framework(self.test_model , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(_SCREAMING_SNAKE_CASE ) UpperCamelCase = FeaturesManager.determine_framework(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(_SCREAMING_SNAKE_CASE ) UpperCamelCase = FeaturesManager.determine_framework(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(_SCREAMING_SNAKE_CASE ) UpperCamelCase = FeaturesManager.determine_framework(_SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(_SCREAMING_SNAKE_CASE ) UpperCamelCase = FeaturesManager.determine_framework(_SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = FeaturesManager.determine_framework(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = MagicMock(return_value=_SCREAMING_SNAKE_CASE ) with patch("""transformers.onnx.features.is_tf_available""" , _SCREAMING_SNAKE_CASE ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_SCREAMING_SNAKE_CASE , self.framework_pt ) # PyTorch not in environment -> use TensorFlow UpperCamelCase = MagicMock(return_value=_SCREAMING_SNAKE_CASE ) with patch("""transformers.onnx.features.is_torch_available""" , _SCREAMING_SNAKE_CASE ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_SCREAMING_SNAKE_CASE , self.framework_tf ) # Both in environment -> use PyTorch UpperCamelCase = MagicMock(return_value=_SCREAMING_SNAKE_CASE ) UpperCamelCase = MagicMock(return_value=_SCREAMING_SNAKE_CASE ) with patch("""transformers.onnx.features.is_tf_available""" , _SCREAMING_SNAKE_CASE ), patch( """transformers.onnx.features.is_torch_available""" , _SCREAMING_SNAKE_CASE ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_SCREAMING_SNAKE_CASE , self.framework_pt ) # Both not in environment -> raise error UpperCamelCase = MagicMock(return_value=_SCREAMING_SNAKE_CASE ) UpperCamelCase = MagicMock(return_value=_SCREAMING_SNAKE_CASE ) with patch("""transformers.onnx.features.is_tf_available""" , _SCREAMING_SNAKE_CASE ), patch( """transformers.onnx.features.is_torch_available""" , _SCREAMING_SNAKE_CASE ): with self.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = FeaturesManager.determine_framework(self.test_model )
718
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) UpperCamelCase = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__UpperCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
35
0
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) class a_ ( lowercase_ ): lowercase = ['''input_features''', '''is_longer'''] def __init__( self , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=48000 , _SCREAMING_SNAKE_CASE=480 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = 14000 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "fusion" , _SCREAMING_SNAKE_CASE = "repeatpad" , **_SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__( feature_size=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , padding_value=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase = top_db UpperCamelCase = truncation UpperCamelCase = padding UpperCamelCase = fft_window_size UpperCamelCase = (fft_window_size >> 1) + 1 UpperCamelCase = hop_length UpperCamelCase = max_length_s UpperCamelCase = max_length_s * sampling_rate UpperCamelCase = sampling_rate UpperCamelCase = frequency_min UpperCamelCase = frequency_max UpperCamelCase = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=_SCREAMING_SNAKE_CASE , min_frequency=_SCREAMING_SNAKE_CASE , max_frequency=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , norm=_SCREAMING_SNAKE_CASE , mel_scale="""htk""" , ) UpperCamelCase = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=_SCREAMING_SNAKE_CASE , min_frequency=_SCREAMING_SNAKE_CASE , max_frequency=_SCREAMING_SNAKE_CASE , sampling_rate=_SCREAMING_SNAKE_CASE , norm="""slaney""" , mel_scale="""slaney""" , ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) UpperCamelCase = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Dict: """simple docstring""" UpperCamelCase = spectrogram( _SCREAMING_SNAKE_CASE , window_function(self.fft_window_size , """hann""" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=_SCREAMING_SNAKE_CASE , log_mel="""dB""" , ) return log_mel_spectrogram.T def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk UpperCamelCase = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk UpperCamelCase = [0] # randomly choose index for each part UpperCamelCase = np.random.choice(ranges[0] ) UpperCamelCase = np.random.choice(ranges[1] ) UpperCamelCase = np.random.choice(ranges[2] ) UpperCamelCase = mel[idx_front : idx_front + chunk_frames, :] UpperCamelCase = mel[idx_middle : idx_middle + chunk_frames, :] UpperCamelCase = mel[idx_back : idx_back + chunk_frames, :] UpperCamelCase = torch.tensor(mel[None, None, :] ) UpperCamelCase = torch.nn.functional.interpolate( _SCREAMING_SNAKE_CASE , size=[chunk_frames, 64] , mode="""bilinear""" , align_corners=_SCREAMING_SNAKE_CASE ) UpperCamelCase = mel_shrink[0][0].numpy() UpperCamelCase = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if waveform.shape[0] > max_length: if truncation == "rand_trunc": UpperCamelCase = True # random crop to max_length (for compatibility) -> this should be handled by self.pad UpperCamelCase = len(_SCREAMING_SNAKE_CASE ) - max_length UpperCamelCase = np.random.randint(0 , overflow + 1 ) UpperCamelCase = waveform[idx : idx + max_length] UpperCamelCase = self._np_extract_fbank_features(_SCREAMING_SNAKE_CASE , self.mel_filters_slaney )[None, :] elif truncation == "fusion": UpperCamelCase = self._np_extract_fbank_features(_SCREAMING_SNAKE_CASE , self.mel_filters ) UpperCamelCase = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed UpperCamelCase = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. UpperCamelCase = np.stack([mel, mel, mel, mel] , axis=0 ) UpperCamelCase = False else: UpperCamelCase = self._random_mel_fusion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = True else: raise NotImplementedError(F"data_truncating {truncation} not implemented" ) else: UpperCamelCase = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": UpperCamelCase = int(max_length / len(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = np.stack(np.tile(_SCREAMING_SNAKE_CASE , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": UpperCamelCase = int(max_length / len(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = np.stack(np.tile(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = np.pad(_SCREAMING_SNAKE_CASE , (0, max_length - waveform.shape[0]) , mode="""constant""" , constant_values=0 ) if truncation == "fusion": UpperCamelCase = self._np_extract_fbank_features(_SCREAMING_SNAKE_CASE , self.mel_filters ) UpperCamelCase = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: UpperCamelCase = self._np_extract_fbank_features(_SCREAMING_SNAKE_CASE , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" UpperCamelCase = truncation if truncation is not None else self.truncation UpperCamelCase = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a" F" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input" F" was sampled with {self.sampling_rate} and not {sampling_rate}." ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) UpperCamelCase = isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"Only mono-channel audio is supported for input to {self}" ) UpperCamelCase = is_batched_numpy or ( isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: UpperCamelCase = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): UpperCamelCase = np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) elif isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): UpperCamelCase = raw_speech.astype(np.floataa ) # always return batch if not is_batched: UpperCamelCase = [np.asarray(_SCREAMING_SNAKE_CASE )] # convert to mel spectrogram, truncate and pad if needed. UpperCamelCase = [ self._get_input_mel(_SCREAMING_SNAKE_CASE , max_length if max_length else self.nb_max_samples , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for waveform in raw_speech ] UpperCamelCase = [] UpperCamelCase = [] for mel, longer in padded_inputs: input_mel.append(_SCREAMING_SNAKE_CASE ) is_longer.append(_SCREAMING_SNAKE_CASE ) if truncation == "fusion" and sum(_SCREAMING_SNAKE_CASE ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer UpperCamelCase = np.random.randint(0 , len(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = True if isinstance(input_mel[0] , _SCREAMING_SNAKE_CASE ): UpperCamelCase = [np.asarray(_SCREAMING_SNAKE_CASE , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool UpperCamelCase = [[longer] for longer in is_longer] UpperCamelCase = {"""input_features""": input_mel, """is_longer""": is_longer} UpperCamelCase = BatchFeature(_SCREAMING_SNAKE_CASE ) if return_tensors is not None: UpperCamelCase = input_features.convert_to_tensors(_SCREAMING_SNAKE_CASE ) return input_features
719
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowercase__ ( __UpperCamelCase , __UpperCamelCase=1 )-> Tuple: if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> Dict: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item.replace("""in_layers.0""" , """norm1""" ) UpperCamelCase = new_item.replace("""in_layers.2""" , """conv1""" ) UpperCamelCase = new_item.replace("""out_layers.0""" , """norm2""" ) UpperCamelCase = new_item.replace("""out_layers.3""" , """conv2""" ) UpperCamelCase = new_item.replace("""emb_layers.1""" , """time_emb_proj""" ) UpperCamelCase = new_item.replace("""skip_connection""" , """conv_shortcut""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> List[str]: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item UpperCamelCase = new_item.replace("""norm.weight""" , """group_norm.weight""" ) UpperCamelCase = new_item.replace("""norm.bias""" , """group_norm.bias""" ) UpperCamelCase = new_item.replace("""proj_out.weight""" , """proj_attn.weight""" ) UpperCamelCase = new_item.replace("""proj_out.bias""" , """proj_attn.bias""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None )-> str: assert isinstance(__UpperCamelCase , __UpperCamelCase ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): UpperCamelCase = old_checkpoint[path] UpperCamelCase = old_tensor.shape[0] // 3 UpperCamelCase = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) UpperCamelCase = old_tensor.shape[0] // config["""num_head_channels"""] // 3 UpperCamelCase = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = old_tensor.split(channels // num_heads , dim=1 ) UpperCamelCase = query.reshape(__UpperCamelCase ) UpperCamelCase = key.reshape(__UpperCamelCase ) UpperCamelCase = value.reshape(__UpperCamelCase ) for path in paths: UpperCamelCase = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here UpperCamelCase = new_path.replace("""middle_block.0""" , """mid_block.resnets.0""" ) UpperCamelCase = new_path.replace("""middle_block.1""" , """mid_block.attentions.0""" ) UpperCamelCase = new_path.replace("""middle_block.2""" , """mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: UpperCamelCase = new_path.replace(replacement["""old"""] , replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: UpperCamelCase = old_checkpoint[path["""old"""]][:, :, 0] else: UpperCamelCase = old_checkpoint[path["""old"""]] def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = {} UpperCamelCase = checkpoint["""time_embed.0.weight"""] UpperCamelCase = checkpoint["""time_embed.0.bias"""] UpperCamelCase = checkpoint["""time_embed.2.weight"""] UpperCamelCase = checkpoint["""time_embed.2.bias"""] UpperCamelCase = checkpoint["""input_blocks.0.0.weight"""] UpperCamelCase = checkpoint["""input_blocks.0.0.bias"""] UpperCamelCase = checkpoint["""out.0.weight"""] UpperCamelCase = checkpoint["""out.0.bias"""] UpperCamelCase = checkpoint["""out.2.weight"""] UpperCamelCase = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"input_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the middle blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"middle_block.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the output blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"output_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } for i in range(1 , __UpperCamelCase ): UpperCamelCase = (i - 1) // (config["""num_res_blocks"""] + 1) UpperCamelCase = (i - 1) % (config["""num_res_blocks"""] + 1) UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.0" in key] UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.1" in key] if F"input_blocks.{i}.0.op.weight" in checkpoint: UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.weight" ] UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.bias" ] continue UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"input_blocks.{i}.0", """new""": F"down_blocks.{block_id}.resnets.{layer_in_block_id}"} UpperCamelCase = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path, resnet_op] , config=__UpperCamelCase ) if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"input_blocks.{i}.1", """new""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"input_blocks.{i}.1.qkv.bias": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"input_blocks.{i}.1.qkv.weight": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase , ) UpperCamelCase = middle_blocks[0] UpperCamelCase = middle_blocks[1] UpperCamelCase = middle_blocks[2] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase ) for i in range(__UpperCamelCase ): UpperCamelCase = i // (config["""num_res_blocks"""] + 1) UpperCamelCase = i % (config["""num_res_blocks"""] + 1) UpperCamelCase = [shave_segments(__UpperCamelCase , 2 ) for name in output_blocks[i]] UpperCamelCase = {} for layer in output_block_layers: UpperCamelCase ,UpperCamelCase = layer.split(""".""" )[0], shave_segments(__UpperCamelCase , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__UpperCamelCase ) else: UpperCamelCase = [layer_name] if len(__UpperCamelCase ) > 1: UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.0" in key] UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.1" in key] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"output_blocks.{i}.0", """new""": F"up_blocks.{block_id}.resnets.{layer_in_block_id}"} assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , config=__UpperCamelCase ) if ["conv.weight", "conv.bias"] in output_block_list.values(): UpperCamelCase = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.weight" ] UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.bias" ] # Clear attentions as they have been attributed above. if len(__UpperCamelCase ) == 2: UpperCamelCase = [] if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"output_blocks.{i}.1", """new""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"output_blocks.{i}.1.qkv.bias": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"output_blocks.{i}.1.qkv.weight": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None , config=__UpperCamelCase , ) else: UpperCamelCase = renew_resnet_paths(__UpperCamelCase , n_shave_prefix_segments=1 ) for path in resnet_0_paths: UpperCamelCase = """.""".join(["""output_blocks""", str(__UpperCamelCase ), path["""old"""]] ) UpperCamelCase = """.""".join(["""up_blocks""", str(__UpperCamelCase ), """resnets""", str(__UpperCamelCase ), path["""new"""]] ) UpperCamelCase = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = torch.load(args.checkpoint_path) with open(args.config_file) as f: SCREAMING_SNAKE_CASE__ = json.loads(f.read()) SCREAMING_SNAKE_CASE__ = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] SCREAMING_SNAKE_CASE__ = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: SCREAMING_SNAKE_CASE__ = DDPMScheduler.from_config('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = VQModel.from_pretrained('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
35
0
import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=14 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , ) -> Any: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_token_type_ids UpperCamelCase = use_input_mask UpperCamelCase = use_labels UpperCamelCase = use_mc_token_ids UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range UpperCamelCase = num_labels UpperCamelCase = num_choices UpperCamelCase = scope UpperCamelCase = self.vocab_size - 1 def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = None if self.use_input_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase = None if self.use_token_type_ids: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase = None if self.use_mc_token_ids: UpperCamelCase = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase = self.get_config() UpperCamelCase = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def A__ ( self ) -> List[Any]: """simple docstring""" return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase = CTRLModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE ) model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase = CTRLLMHeadModel(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() ( ( UpperCamelCase ) ,( UpperCamelCase ) ,( UpperCamelCase ) ,( UpperCamelCase ) ,( UpperCamelCase ) ,( UpperCamelCase ) ,( UpperCamelCase ) ,( UpperCamelCase ) ,( UpperCamelCase ) , ) = config_and_inputs UpperCamelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask} return config, inputs_dict def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = CTRLForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () lowercase = (CTRLLMHeadModel,) if is_torch_available() else () lowercase = ( { """feature-extraction""": CTRLModel, """text-classification""": CTRLForSequenceClassification, """text-generation""": CTRLLMHeadModel, """zero-shot""": CTRLForSequenceClassification, } if is_torch_available() else {} ) lowercase = True lowercase = False lowercase = False def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = CTRLModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , n_embd=37 ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def A__ ( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_SCREAMING_SNAKE_CASE ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def A__ ( self ) -> Dict: """simple docstring""" pass @slow def A__ ( self ) -> Optional[Any]: """simple docstring""" for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = CTRLModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @unittest.skip("""The model doesn\'t support left padding""" ) # and it's not used enough to be worth fixing :) def A__ ( self ) -> Tuple: """simple docstring""" pass @require_torch class a_ ( unittest.TestCase ): def A__ ( self ) -> str: """simple docstring""" super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = CTRLLMHeadModel.from_pretrained("""ctrl""" ) model.to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.tensor( [[11859, 0, 1611, 8]] , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) # Legal the president is UpperCamelCase = [ 11859, 0, 1611, 8, 5, 150, 26449, 2, 19, 348, 469, 3, 2595, 48, 20740, 246533, 246533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a UpperCamelCase = model.generate(_SCREAMING_SNAKE_CASE , do_sample=_SCREAMING_SNAKE_CASE ) self.assertListEqual(output_ids[0].tolist() , _SCREAMING_SNAKE_CASE )
720
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' import os from pathlib import Path def lowercase__ ( )-> Any: from torch.utils.cpp_extension import load UpperCamelCase = Path(__UpperCamelCase ).resolve().parent.parent.parent / """kernels""" / """deformable_detr""" UpperCamelCase = [ root / filename for filename in [ """vision.cpp""", os.path.join("""cpu""" , """ms_deform_attn_cpu.cpp""" ), os.path.join("""cuda""" , """ms_deform_attn_cuda.cu""" ), ] ] load( """MultiScaleDeformableAttention""" , __UpperCamelCase , with_cuda=__UpperCamelCase , extra_include_paths=[str(__UpperCamelCase )] , extra_cflags=["""-DWITH_CUDA=1"""] , extra_cuda_cflags=[ """-DCUDA_HAS_FP16=1""", """-D__CUDA_NO_HALF_OPERATORS__""", """-D__CUDA_NO_HALF_CONVERSIONS__""", """-D__CUDA_NO_HALF2_OPERATORS__""", ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
721
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration SCREAMING_SNAKE_CASE__ = 'facebook/wmt19-en-de' SCREAMING_SNAKE_CASE__ = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model SCREAMING_SNAKE_CASE__ = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) SCREAMING_SNAKE_CASE__ = FSMTForConditionalGeneration(config) print(f'num of params {tiny_model.num_parameters()}') # Test SCREAMING_SNAKE_CASE__ = tokenizer(['Making tiny model'], return_tensors='pt') SCREAMING_SNAKE_CASE__ = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save SCREAMING_SNAKE_CASE__ = 'tiny-wmt19-en-de' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f'Generated {mname_tiny}') # Upload # transformers-cli upload tiny-wmt19-en-de
35
0
'''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 a_ ( unittest.TestCase ): def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """的""", """价""", """格""", """是""", """15""", """便""", """alex""", """##andra""", """,""", """。""", """-""", """t""", """shirt""", ] UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) UpperCamelCase = { """do_resize""": True, """size""": {"""height""": 224, """width""": 224}, """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, } UpperCamelCase = os.path.join(self.tmpdirname , _SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] UpperCamelCase = [Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.get_tokenizer() UpperCamelCase = self.get_rust_tokenizer() UpperCamelCase = self.get_image_processor() UpperCamelCase = ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) UpperCamelCase = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_SCREAMING_SNAKE_CASE ) UpperCamelCase = ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) UpperCamelCase = 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 , _SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , _SCREAMING_SNAKE_CASE ) 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 , _SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase = self.get_tokenizer(cls_token="""(CLS)""" , sep_token="""(SEP)""" ) UpperCamelCase = self.get_image_processor(do_normalize=_SCREAMING_SNAKE_CASE ) UpperCamelCase = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="""(CLS)""" , sep_token="""(SEP)""" , do_normalize=_SCREAMING_SNAKE_CASE ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.prepare_image_inputs() UpperCamelCase = image_processor(_SCREAMING_SNAKE_CASE , return_tensors="""np""" ) UpperCamelCase = processor(images=_SCREAMING_SNAKE_CASE , 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 A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) UpperCamelCase = """Alexandra,T-shirt的价格是15便士。""" UpperCamelCase = processor(text=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer(_SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) UpperCamelCase = """Alexandra,T-shirt的价格是15便士。""" UpperCamelCase = self.prepare_image_inputs() UpperCamelCase = processor(text=_SCREAMING_SNAKE_CASE , images=_SCREAMING_SNAKE_CASE ) 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(_SCREAMING_SNAKE_CASE ): processor() def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase = processor.batch_decode(_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.get_image_processor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ChineseCLIPProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) UpperCamelCase = """Alexandra,T-shirt的价格是15便士。""" UpperCamelCase = self.prepare_image_inputs() UpperCamelCase = processor(text=_SCREAMING_SNAKE_CASE , images=_SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
700
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) SCREAMING_SNAKE_CASE__ = CLIPImageProcessor() SCREAMING_SNAKE_CASE__ = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') SCREAMING_SNAKE_CASE__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> str: if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase = """""" while len(__UpperCamelCase ) % 3 != 0: UpperCamelCase = """0""" + bin_string UpperCamelCase = [ bin_string[index : index + 3] for index in range(len(__UpperCamelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase = 0 for index, val in enumerate(__UpperCamelCase ): oct_val += int(2 ** (2 - index) * int(__UpperCamelCase ) ) oct_string += str(__UpperCamelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
701
'''simple docstring''' from __future__ import annotations from typing import Any class a_ : def __init__( self , _SCREAMING_SNAKE_CASE = 6 ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None self.create_linked_list(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = current_node UpperCamelCase = current_node for _ in range(1 , _SCREAMING_SNAKE_CASE ): UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = previous_node UpperCamelCase = current_node UpperCamelCase = self.front UpperCamelCase = previous_node def A__ ( self ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCamelCase = self.rear.next if self.rear: UpperCamelCase = data def A__ ( self ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCamelCase = self.front.data UpperCamelCase = None return data UpperCamelCase = self.front UpperCamelCase = old_front.next UpperCamelCase = old_front.data UpperCamelCase = None return data def A__ ( self ) -> None: """simple docstring""" if self.is_empty(): raise Exception("""Empty Queue""" ) def A__ ( self ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class a_ : def __init__( self ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): @slow def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) UpperCamelCase = { """input_ids""": tf.convert_to_tensor([[0, 2646, 10269, 83, 99942, 2]] , dtype=tf.intaa ), # "My dog is cute" """attention_mask""": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } UpperCamelCase = model(_SCREAMING_SNAKE_CASE )["""last_hidden_state"""] UpperCamelCase = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) # compare the actual values for a slice. UpperCamelCase = tf.convert_to_tensor( [ [ [0.0_6_8_1_7_6_2, 0.1_0_8_9_4_4_5_1, 0.0_6_7_7_2_5_0_4], [-0.0_6_4_2_3_6_6_8, 0.0_2_3_6_6_6_1_5, 0.0_4_3_2_9_3_4_4], [-0.0_6_0_5_7_2_9_5, 0.0_9_9_7_4_1_3_5, -0.0_0_0_7_0_5_8_4], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
702
'''simple docstring''' import fire from utils import calculate_rouge, save_json def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , **__UpperCamelCase )-> int: UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()] UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()][: len(__UpperCamelCase )] UpperCamelCase = calculate_rouge(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) if save_path is not None: save_json(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
35
0
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig 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 SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=224 , _SCREAMING_SNAKE_CASE=1000 , _SCREAMING_SNAKE_CASE=[3, 3, 6, 4] , _SCREAMING_SNAKE_CASE=[48, 56, 112, 220] , ) -> Any: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = num_labels UpperCamelCase = image_size UpperCamelCase = layer_depths UpperCamelCase = embed_dims def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels def A__ ( self ) -> Tuple: """simple docstring""" return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=_SCREAMING_SNAKE_CASE , layer_scale_init_value=1e-5 , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = SwiftFormerModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) UpperCamelCase = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A__ ( self ) -> Tuple: """simple docstring""" ((UpperCamelCase) ,(UpperCamelCase) ,(UpperCamelCase)) = self.prepare_config_and_inputs() UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () lowercase = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) lowercase = False lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = SwiftFormerModelTester(self ) UpperCamelCase = ConfigTester( self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def A__ ( self ) -> int: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def A__ ( self ) -> int: """simple docstring""" pass def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def A__ ( self ) -> Dict: """simple docstring""" for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = SwiftFormerModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def A__ ( self ) -> str: """simple docstring""" pass def A__ ( self ) -> Optional[int]: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = 8 self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(_SCREAMING_SNAKE_CASE ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[str]: """simple docstring""" def _config_zero_init(_SCREAMING_SNAKE_CASE ): UpperCamelCase = copy.deepcopy(_SCREAMING_SNAKE_CASE ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1e-10 ) if isinstance(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ): UpperCamelCase = _config_zero_init(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return configs_no_init UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = _config_zero_init(_SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: UpperCamelCase = model_class(config=_SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9) / 1e9).round().item() , [0.0, 1.0] , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def A__ ( self ) -> int: """simple docstring""" pass def lowercase__ ( )-> List[Any]: UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def A__ ( self ) -> str: """simple docstring""" return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits UpperCamelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.tensor([[-2.17_03e00, 2.11_07e00, -2.08_11e00]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
703
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> tuple[float, list[float]]: UpperCamelCase = list(range(len(__UpperCamelCase ) ) ) UpperCamelCase = [v / w for v, w in zip(__UpperCamelCase , __UpperCamelCase )] index.sort(key=lambda __UpperCamelCase : ratio[i] , reverse=__UpperCamelCase ) UpperCamelCase = 0 UpperCamelCase = [0] * len(__UpperCamelCase ) for i in index: if weight[i] <= capacity: UpperCamelCase = 1 max_value += value[i] capacity -= weight[i] else: UpperCamelCase = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class a_ ( lowerCamelCase ): lowercase = ( """This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.""" """It takes two arguments named `image` which should be the original image, and `label` which should be a text """ """describing the elements what should be identified in the segmentation mask. The tool returns the mask.""" ) lowercase = """CIDAS/clipseg-rd64-refined""" lowercase = """image_segmenter""" lowercase = CLIPSegForImageSegmentation lowercase = ["""image""", """text"""] lowercase = ["""image"""] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" requires_backends(self , ["""vision"""] ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.pre_processor(text=[label] , images=[image] , padding=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" with torch.no_grad(): UpperCamelCase = self.model(**_SCREAMING_SNAKE_CASE ).logits return logits def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = outputs.cpu().detach().numpy() UpperCamelCase = 0 UpperCamelCase = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
704
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a_ ( lowerCamelCase ): lowercase = """deformable_detr""" lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # deformable attributes UpperCamelCase = num_feature_levels UpperCamelCase = encoder_n_points UpperCamelCase = decoder_n_points UpperCamelCase = two_stage UpperCamelCase = two_stage_num_proposals UpperCamelCase = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient UpperCamelCase = focal_alpha UpperCamelCase = disable_custom_kernels super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A__ ( self ) -> int: """simple docstring""" return self.d_model def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output
35
0
'''simple docstring''' import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = IFPipeline lowercase = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} lowercase = TEXT_TO_IMAGE_BATCH_PARAMS lowercase = PipelineTesterMixin.required_optional_params - {"""latents"""} def A__ ( self ) -> Any: """simple docstring""" return self._get_dummy_components() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> Union[str, Any]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith("""mps""" ): UpperCamelCase = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def A__ ( self ) -> Dict: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def A__ ( self ) -> Optional[int]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def A__ ( self ) -> Any: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def A__ ( self ) -> Tuple: """simple docstring""" self._test_save_load_local() def A__ ( self ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def A__ ( self ) -> Tuple: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): def A__ ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase = IFSuperResolutionPipeline.from_pretrained( """DeepFloyd/IF-II-L-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("""cuda""" ) UpperCamelCase ,UpperCamelCase = pipe_a.encode_prompt("""anime turtle""" , device="""cuda""" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() UpperCamelCase = None UpperCamelCase = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img UpperCamelCase = IFImgaImgPipeline(**pipe_a.components ) UpperCamelCase = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting UpperCamelCase = IFInpaintingPipeline(**pipe_a.components ) UpperCamelCase = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (64, 64, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy""" ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (256, 256, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _start_torch_memory_measurement() UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (64, 64, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy""" ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , original_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (256, 256, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _start_torch_memory_measurement() UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (64, 64, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy""" ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , original_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (256, 256, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase__ ( )-> Tuple: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
705
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowercase__ ( __UpperCamelCase )-> Any: UpperCamelCase = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase ,UpperCamelCase = emb.weight.shape UpperCamelCase = nn.Linear(__UpperCamelCase , __UpperCamelCase , bias=__UpperCamelCase ) UpperCamelCase = emb.weight.data return lin_layer def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase = torch.load(__UpperCamelCase , map_location="""cpu""" ) UpperCamelCase = mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""] UpperCamelCase = mam_aaa["""model"""] remove_ignore_keys_(__UpperCamelCase ) UpperCamelCase = state_dict["""encoder.embed_tokens.weight"""].shape[0] UpperCamelCase = MaMaaaConfig( vocab_size=__UpperCamelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , ) UpperCamelCase = state_dict["""decoder.embed_tokens.weight"""] UpperCamelCase = MaMaaaForConditionalGeneration(__UpperCamelCase ) model.model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) UpperCamelCase = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
35
0
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__ = 1_6 SCREAMING_SNAKE_CASE__ = 3_2 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 16 )-> Optional[int]: UpperCamelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase = DatasetDict( { """train""": dataset["""train"""].select(__UpperCamelCase ), """validation""": dataset["""train"""].select(__UpperCamelCase ), """test""": dataset["""validation"""], } ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__UpperCamelCase , max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__UpperCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase = 16 elif accelerator.mixed_precision != "no": UpperCamelCase = 8 else: UpperCamelCase = None return tokenizer.pad( __UpperCamelCase , padding="""longest""" , max_length=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. UpperCamelCase = DataLoader( tokenized_datasets["""train"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) UpperCamelCase = DataLoader( tokenized_datasets["""validation"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) UpperCamelCase = DataLoader( tokenized_datasets["""test"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader, test_dataloader def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Any: # New Code # UpperCamelCase = [] # Download the dataset UpperCamelCase = load_dataset("""glue""" , """mrpc""" ) # Create our splits UpperCamelCase = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator UpperCamelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase = config["""lr"""] UpperCamelCase = int(config["""num_epochs"""] ) UpperCamelCase = int(config["""seed"""] ) UpperCamelCase = int(config["""batch_size"""] ) UpperCamelCase = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation UpperCamelCase = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: UpperCamelCase = batch_size // MAX_GPU_BATCH_SIZE UpperCamelCase = MAX_GPU_BATCH_SIZE set_seed(__UpperCamelCase ) # New Code # # Create our folds: UpperCamelCase = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) UpperCamelCase = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__UpperCamelCase ): UpperCamelCase ,UpperCamelCase ,UpperCamelCase = get_fold_dataloaders( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase = AdamW(params=model.parameters() , lr=__UpperCamelCase ) # Instantiate scheduler UpperCamelCase = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase , num_warmup_steps=100 , num_training_steps=(len(__UpperCamelCase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = accelerator.prepare( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Now we train the model for epoch in range(__UpperCamelCase ): model.train() for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = outputs.loss UpperCamelCase = loss / gradient_accumulation_steps accelerator.backward(__UpperCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = outputs.logits.argmax(dim=-1 ) UpperCamelCase ,UpperCamelCase = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__UpperCamelCase , references=__UpperCamelCase , ) UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __UpperCamelCase ) # New Code # # We also run predictions on the test set at the very end UpperCamelCase = [] for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = outputs.logits UpperCamelCase ,UpperCamelCase = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__UpperCamelCase , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: UpperCamelCase = torch.cat(__UpperCamelCase , dim=0 ) UpperCamelCase = torch.stack(__UpperCamelCase , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) UpperCamelCase = metric.compute(predictions=__UpperCamelCase , references=__UpperCamelCase ) accelerator.print("""Average test metrics from all folds:""" , __UpperCamelCase ) def lowercase__ ( )-> List[str]: UpperCamelCase = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__UpperCamelCase , default=__UpperCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=__UpperCamelCase , default=3 , help="""The number of splits to perform across the dataset""" ) UpperCamelCase = parser.parse_args() UpperCamelCase = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
706
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class a_ ( lowerCamelCase ): def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """tf_padding""" ) ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """depth_multiplier""" ) ) class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE="relu6" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=None , ) -> List[str]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = depth_multiplier UpperCamelCase = min_depth UpperCamelCase = tf_padding UpperCamelCase = int(last_hidden_size * depth_multiplier ) UpperCamelCase = output_stride UpperCamelCase = hidden_act UpperCamelCase = classifier_dropout_prob UpperCamelCase = use_labels UpperCamelCase = is_training UpperCamelCase = num_labels UpperCamelCase = initializer_range UpperCamelCase = scope def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels, pixel_labels def A__ ( self ) -> Optional[Any]: """simple docstring""" return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = MobileNetVaForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowercase = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModelTester(self ) UpperCamelCase = MobileNetVaConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not output attentions""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = 26 self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def A__ ( self ) -> Dict: """simple docstring""" for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = MobileNetVaModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowercase__ ( )-> Optional[Any]: UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def A__ ( self ) -> Dict: """simple docstring""" return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224""" ) if is_vision_available() else None ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224""" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits UpperCamelCase = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
35
0
'''simple docstring''' import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class a_ ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=False , ) -> List[Any]: """simple docstring""" UpperCamelCase = size if size is not None else {"""height""": 20, """width""": 20} UpperCamelCase = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = min_resolution UpperCamelCase = max_resolution UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = do_center_crop UpperCamelCase = crop_size UpperCamelCase = do_normalize UpperCamelCase = image_mean UpperCamelCase = image_std UpperCamelCase = do_reduce_labels def A__ ( self ) -> Dict: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def lowercase__ ( )-> Union[str, Any]: UpperCamelCase = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) UpperCamelCase = Image.open(dataset[0]["""file"""] ) UpperCamelCase = Image.open(dataset[1]["""file"""] ) return image, map def lowercase__ ( )-> List[Any]: UpperCamelCase = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) UpperCamelCase = Image.open(ds[0]["""file"""] ) UpperCamelCase = Image.open(ds[1]["""file"""] ) UpperCamelCase = Image.open(ds[2]["""file"""] ) UpperCamelCase = Image.open(ds[3]["""file"""] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class a_ ( lowerCamelCase , unittest.TestCase ): lowercase = BeitImageProcessor if is_vision_available() else None def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = BeitImageProcessingTester(self ) @property def A__ ( self ) -> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """size""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """do_center_crop""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """center_crop""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """image_std""" ) ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 20, """width""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) self.assertEqual(image_processor.do_reduce_labels , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) self.assertEqual(image_processor.do_reduce_labels , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" pass def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , numpify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def A__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) UpperCamelCase = [] for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , maps[0] , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test not batched input (PIL images) UpperCamelCase ,UpperCamelCase = prepare_semantic_single_inputs() UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched input (PIL images) UpperCamelCase ,UpperCamelCase = prepare_semantic_batch_inputs() UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 2, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 UpperCamelCase ,UpperCamelCase = prepare_semantic_single_inputs() UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 150 ) UpperCamelCase = True UpperCamelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 )
707
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-1' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-2' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-3' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-4' class a_ ( lowerCamelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , ) -> Any: """simple docstring""" super()._init_() UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline( vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , requires_safety_checker=_SCREAMING_SNAKE_CASE , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def A__ ( self ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , _SCREAMING_SNAKE_CASE ) for k in self.config.keys() if not k.startswith("""_""" )} def A__ ( self , _SCREAMING_SNAKE_CASE = "auto" ) -> Optional[Any]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" self.enable_attention_slicing(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" UpperCamelCase = """cuda""" if torch.cuda.is_available() else """cpu""" self.to(_SCREAMING_SNAKE_CASE ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
35
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) def lowercase__ ( __UpperCamelCase )-> int: # initialize config if "resnet-50" in model_name: UpperCamelCase = ResNetConfig.from_pretrained("""microsoft/resnet-50""" ) elif "resnet-101" in model_name: UpperCamelCase = ResNetConfig.from_pretrained("""microsoft/resnet-101""" ) else: raise ValueError("""Model name should include either resnet50 or resnet101""" ) UpperCamelCase = DetrConfig(use_timm_backbone=__UpperCamelCase , backbone_config=__UpperCamelCase ) # set label attributes UpperCamelCase = """panoptic""" in model_name if is_panoptic: UpperCamelCase = 250 else: UpperCamelCase = 91 UpperCamelCase = """huggingface/label-files""" UpperCamelCase = """coco-detection-id2label.json""" UpperCamelCase = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) UpperCamelCase = {int(__UpperCamelCase ): v for k, v in idalabel.items()} UpperCamelCase = idalabel UpperCamelCase = {v: k for k, v in idalabel.items()} return config, is_panoptic def lowercase__ ( __UpperCamelCase )-> List[Any]: # here we list all keys to be renamed (original name on the left, our name on the right) UpperCamelCase = [] # stem # fmt: off rename_keys.append(("""backbone.0.body.conv1.weight""", """backbone.conv_encoder.model.embedder.embedder.convolution.weight""") ) rename_keys.append(("""backbone.0.body.bn1.weight""", """backbone.conv_encoder.model.embedder.embedder.normalization.weight""") ) rename_keys.append(("""backbone.0.body.bn1.bias""", """backbone.conv_encoder.model.embedder.embedder.normalization.bias""") ) rename_keys.append(("""backbone.0.body.bn1.running_mean""", """backbone.conv_encoder.model.embedder.embedder.normalization.running_mean""") ) rename_keys.append(("""backbone.0.body.bn1.running_var""", """backbone.conv_encoder.model.embedder.embedder.normalization.running_var""") ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( F"transformer.encoder.layers.{i}.self_attn.out_proj.weight", F"encoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.encoder.layers.{i}.self_attn.out_proj.bias", F"encoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.weight", F"encoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.bias", F"encoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.weight", F"encoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.bias", F"encoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.weight", F"encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.bias", F"encoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm2.weight", F"encoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.norm2.bias", F"encoder.layers.{i}.final_layer_norm.bias") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( F"transformer.decoder.layers.{i}.self_attn.out_proj.weight", F"decoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.decoder.layers.{i}.self_attn.out_proj.bias", F"decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", F"decoder.layers.{i}.encoder_attn.out_proj.weight", ) ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", F"decoder.layers.{i}.encoder_attn.out_proj.bias", ) ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.weight", F"decoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.bias", F"decoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.weight", F"decoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.bias", F"decoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.weight", F"decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.bias", F"decoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.weight", F"decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.bias", F"decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm3.weight", F"decoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.norm3.bias", F"decoder.layers.{i}.final_layer_norm.bias") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("""input_proj.weight""", """input_projection.weight"""), ("""input_proj.bias""", """input_projection.bias"""), ("""query_embed.weight""", """query_position_embeddings.weight"""), ("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""), ("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""), ("""class_embed.weight""", """class_labels_classifier.weight"""), ("""class_embed.bias""", """class_labels_classifier.bias"""), ("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""), ("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""), ("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""), ("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""), ("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""), ("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""), ] ) return rename_keys def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = state_dict.pop(__UpperCamelCase ) UpperCamelCase = val def lowercase__ ( __UpperCamelCase , __UpperCamelCase=False )-> Optional[Any]: UpperCamelCase = """""" if is_panoptic: UpperCamelCase = """detr.""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) UpperCamelCase = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight" ) UpperCamelCase = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase = in_proj_weight[:256, :] UpperCamelCase = in_proj_bias[:256] UpperCamelCase = in_proj_weight[256:512, :] UpperCamelCase = in_proj_bias[256:512] UpperCamelCase = in_proj_weight[-256:, :] UpperCamelCase = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention UpperCamelCase = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) UpperCamelCase = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase = in_proj_weight[:256, :] UpperCamelCase = in_proj_bias[:256] UpperCamelCase = in_proj_weight[256:512, :] UpperCamelCase = in_proj_bias[256:512] UpperCamelCase = in_proj_weight[-256:, :] UpperCamelCase = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention UpperCamelCase = state_dict.pop( F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight" ) UpperCamelCase = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias" ) # next, add query, keys and values (in that order) of cross-attention to the state dict UpperCamelCase = in_proj_weight_cross_attn[:256, :] UpperCamelCase = in_proj_bias_cross_attn[:256] UpperCamelCase = in_proj_weight_cross_attn[256:512, :] UpperCamelCase = in_proj_bias_cross_attn[256:512] UpperCamelCase = in_proj_weight_cross_attn[-256:, :] UpperCamelCase = in_proj_bias_cross_attn[-256:] def lowercase__ ( )-> Optional[Any]: UpperCamelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCamelCase = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ) return im @torch.no_grad() def lowercase__ ( __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=False )-> Optional[Any]: UpperCamelCase ,UpperCamelCase = get_detr_config(__UpperCamelCase ) # load original model from torch hub UpperCamelCase = { """detr-resnet-50""": """detr_resnet50""", """detr-resnet-101""": """detr_resnet101""", } logger.info(F"Converting model {model_name}..." ) UpperCamelCase = torch.hub.load("""facebookresearch/detr""" , model_name_to_original_name[model_name] , pretrained=__UpperCamelCase ).eval() UpperCamelCase = detr.state_dict() # rename keys for src, dest in create_rename_keys(__UpperCamelCase ): if is_panoptic: UpperCamelCase = """detr.""" + src rename_key(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__UpperCamelCase , is_panoptic=__UpperCamelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them UpperCamelCase = """detr.model.""" if is_panoptic else """model.""" for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("""detr""" ) and not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ) ): UpperCamelCase = state_dict.pop(__UpperCamelCase ) UpperCamelCase = val elif "class_labels_classifier" in key or "bbox_predictor" in key: UpperCamelCase = state_dict.pop(__UpperCamelCase ) UpperCamelCase = val elif key.startswith("""bbox_attention""" ) or key.startswith("""mask_head""" ): continue else: UpperCamelCase = state_dict.pop(__UpperCamelCase ) UpperCamelCase = val else: if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): UpperCamelCase = state_dict.pop(__UpperCamelCase ) UpperCamelCase = val # finally, create HuggingFace model and load state dict UpperCamelCase = DetrForSegmentation(__UpperCamelCase ) if is_panoptic else DetrForObjectDetection(__UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) model.eval() # verify our conversion on an image UpperCamelCase = """coco_panoptic""" if is_panoptic else """coco_detection""" UpperCamelCase = DetrImageProcessor(format=__UpperCamelCase ) UpperCamelCase = processor(images=prepare_img() , return_tensors="""pt""" ) UpperCamelCase = encoding["""pixel_values"""] UpperCamelCase = detr(__UpperCamelCase ) UpperCamelCase = model(__UpperCamelCase ) assert torch.allclose(outputs.logits , original_outputs["""pred_logits"""] , atol=1E-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs["""pred_boxes"""] , atol=1E-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["""pred_masks"""] , atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F"Saving PyTorch model and image processor to {pytorch_dump_folder_path}..." ) Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) model.save_pretrained(__UpperCamelCase ) processor.save_pretrained(__UpperCamelCase ) if push_to_hub: # Upload model and image processor to the hub logger.info("""Uploading PyTorch model and image processor to the hub...""" ) model.push_to_hub(F"nielsr/{model_name}" ) processor.push_to_hub(F"nielsr/{model_name}" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
708
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE__ = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' import requests from bsa import BeautifulSoup def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: UpperCamelCase = BeautifulSoup(requests.get(__UpperCamelCase , params=__UpperCamelCase ).content , """html.parser""" ) UpperCamelCase = soup.find("""div""" , attrs={"""class""": """gs_ri"""} ) UpperCamelCase = div.find("""div""" , attrs={"""class""": """gs_fl"""} ).find_all("""a""" ) return anchors[2].get_text() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 3_0, 'pages': '3979-3990', 'year': 2_0_1_8, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
709
'''simple docstring''' SCREAMING_SNAKE_CASE__ = 8.31_44_62 # Unit - J mol-1 K-1 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowercase__ ( __UpperCamelCase=None )-> Union[str, Any]: if subparsers is not None: UpperCamelCase = subparsers.add_parser("""env""" ) else: UpperCamelCase = argparse.ArgumentParser("""Accelerate env command""" ) parser.add_argument( """--config_file""" , default=__UpperCamelCase , help="""The config file to use for the default values in the launching script.""" ) if subparsers is not None: parser.set_defaults(func=__UpperCamelCase ) return parser def lowercase__ ( __UpperCamelCase )-> List[str]: UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = is_xpu_available() UpperCamelCase = is_npu_available() UpperCamelCase = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(__UpperCamelCase ): UpperCamelCase = load_config_from_file(args.config_file ).to_dict() UpperCamelCase = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """PyTorch XPU available""": str(__UpperCamelCase ), """PyTorch NPU available""": str(__UpperCamelCase ), """System RAM""": F"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", } if pt_cuda_available: UpperCamelCase = torch.cuda.get_device_name() print("""\nCopy-and-paste the text below in your GitHub issue\n""" ) print("""\n""".join([F"- {prop}: {val}" for prop, val in info.items()] ) ) print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" ) UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else F"\t{accelerate_config}" ) print(__UpperCamelCase ) UpperCamelCase = accelerate_config return info def lowercase__ ( )-> int: UpperCamelCase = env_command_parser() UpperCamelCase = parser.parse_args() env_command(__UpperCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
710
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__ = 1_6 SCREAMING_SNAKE_CASE__ = 3_2 def lowercase__ ( __UpperCamelCase , __UpperCamelCase = 16 )-> Dict: UpperCamelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__UpperCamelCase , max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__UpperCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase = 16 elif accelerator.mixed_precision != "no": UpperCamelCase = 8 else: UpperCamelCase = None return tokenizer.pad( __UpperCamelCase , padding="""longest""" , max_length=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. UpperCamelCase = DataLoader( tokenized_datasets["""train"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) UpperCamelCase = DataLoader( tokenized_datasets["""validation"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE__ = mocked_dataloaders # noqa: F811 def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List[Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __UpperCamelCase ) == "1": UpperCamelCase = 2 # New Code # UpperCamelCase = int(args.gradient_accumulation_steps ) UpperCamelCase = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__UpperCamelCase ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase = config["""lr"""] UpperCamelCase = int(config["""num_epochs"""] ) UpperCamelCase = int(config["""seed"""] ) UpperCamelCase = int(config["""batch_size"""] ) UpperCamelCase = evaluate.load("""glue""" , """mrpc""" ) set_seed(__UpperCamelCase ) UpperCamelCase ,UpperCamelCase = get_dataloaders(__UpperCamelCase , __UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase = AdamW(params=model.parameters() , lr=__UpperCamelCase ) # Instantiate scheduler UpperCamelCase = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase , num_warmup_steps=100 , num_training_steps=(len(__UpperCamelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = accelerator.prepare( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Now we train the model for epoch in range(__UpperCamelCase ): model.train() with LocalSGD( accelerator=__UpperCamelCase , model=__UpperCamelCase , local_sgd_steps=__UpperCamelCase , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__UpperCamelCase ): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = output.loss accelerator.backward(__UpperCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = outputs.logits.argmax(dim=-1 ) UpperCamelCase ,UpperCamelCase = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__UpperCamelCase , references=__UpperCamelCase , ) UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __UpperCamelCase ) def lowercase__ ( )-> List[Any]: UpperCamelCase = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__UpperCamelCase , default=__UpperCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__UpperCamelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument( """--local_sgd_steps""" , type=__UpperCamelCase , default=8 , help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) UpperCamelCase = parser.parse_args() UpperCamelCase = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase = 100 )-> int: UpperCamelCase = set() UpperCamelCase = 0 UpperCamelCase = n + 1 # maximum limit for a in range(2 , __UpperCamelCase ): for b in range(2 , __UpperCamelCase ): UpperCamelCase = a**b # calculates the current power collect_powers.add(__UpperCamelCase ) # adds the result to the set return len(__UpperCamelCase ) if __name__ == "__main__": print('Number of terms ', solution(int(str(input()).strip())))
711
'''simple docstring''' import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> Any: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = embed_dim UpperCamelCase = depths 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 = patch_norm UpperCamelCase = layer_norm_eps UpperCamelCase = initializer_range UpperCamelCase = is_training UpperCamelCase = scope UpperCamelCase = use_labels UpperCamelCase = type_sequence_label_size UpperCamelCase = encoder_stride UpperCamelCase = out_features UpperCamelCase = out_indices def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = self.get_config() return config, pixel_values, labels def A__ ( self ) -> str: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) UpperCamelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = ["""stem"""] UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowercase = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {} lowercase = False lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with""" """ `nn.DataParallel`""" ) ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self ) -> Dict: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A__ ( self ) -> int: """simple docstring""" return def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip("""Swin does not use inputs_embeds""" ) def A__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip("""Swin does not support feedforward chunking""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" ) def A__ ( self ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = 3 UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> List[Any]: """simple docstring""" pass def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): UpperCamelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( """Tuple and dict output are not equal. Difference:""" F" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:" F" {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has" F" `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}." ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) @require_torch class a_ ( unittest.TestCase , lowerCamelCase ): lowercase = (MaskFormerSwinBackbone,) if is_torch_available() else () lowercase = MaskFormerSwinConfig def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = inputs_dict["""pixel_values"""].shape[0] for backbone_class in self.all_model_classes: UpperCamelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
35
0
'''simple docstring''' import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} SCREAMING_SNAKE_CASE__ = { 'vocab_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE__ = { 'vocab_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE__ = { 'vocab_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE__ = { 'facebook/dpr-ctx_encoder-single-nq-base': 5_1_2, 'facebook/dpr-ctx_encoder-multiset-base': 5_1_2, } SCREAMING_SNAKE_CASE__ = { 'facebook/dpr-question_encoder-single-nq-base': 5_1_2, 'facebook/dpr-question_encoder-multiset-base': 5_1_2, } SCREAMING_SNAKE_CASE__ = { 'facebook/dpr-reader-single-nq-base': 5_1_2, 'facebook/dpr-reader-multiset-base': 5_1_2, } SCREAMING_SNAKE_CASE__ = { 'facebook/dpr-ctx_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-ctx_encoder-multiset-base': {'do_lower_case': True}, } SCREAMING_SNAKE_CASE__ = { 'facebook/dpr-question_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-question_encoder-multiset-base': {'do_lower_case': True}, } SCREAMING_SNAKE_CASE__ = { 'facebook/dpr-reader-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-reader-multiset-base': {'do_lower_case': True}, } class a_ ( lowerCamelCase ): lowercase = VOCAB_FILES_NAMES lowercase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP lowercase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class a_ ( lowerCamelCase ): lowercase = VOCAB_FILES_NAMES lowercase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP lowercase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE__ = collections.namedtuple( 'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text'] ) SCREAMING_SNAKE_CASE__ = collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits']) SCREAMING_SNAKE_CASE__ = R'\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n ```\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n ```\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n - `\'np\'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Returns:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n ' @add_start_docstrings(lowerCamelCase ) class a_ : def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> BatchEncoding: """simple docstring""" if titles is None and texts is None: return super().__call__( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) elif titles is None or texts is None: UpperCamelCase = titles if texts is None else texts return super().__call__( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase = titles if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else [titles] UpperCamelCase = texts if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else [texts] UpperCamelCase = len(_SCREAMING_SNAKE_CASE ) UpperCamelCase = questions if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else [questions] * n_passages if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError( F"There should be as many titles than texts but got {len(_SCREAMING_SNAKE_CASE )} titles and {len(_SCREAMING_SNAKE_CASE )} texts." ) UpperCamelCase = super().__call__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE )["""input_ids"""] UpperCamelCase = super().__call__(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE )["""input_ids"""] UpperCamelCase = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] } if return_attention_mask is not False: UpperCamelCase = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) UpperCamelCase = attention_mask return self.pad(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 16 , _SCREAMING_SNAKE_CASE = 64 , _SCREAMING_SNAKE_CASE = 4 , ) -> List[DPRSpanPrediction]: """simple docstring""" UpperCamelCase = reader_input["""input_ids"""] UpperCamelCase ,UpperCamelCase ,UpperCamelCase = reader_output[:3] UpperCamelCase = len(_SCREAMING_SNAKE_CASE ) UpperCamelCase = sorted(range(_SCREAMING_SNAKE_CASE ) , reverse=_SCREAMING_SNAKE_CASE , key=relevance_logits.__getitem__ ) UpperCamelCase = [] for doc_id in sorted_docs: UpperCamelCase = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence UpperCamelCase = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: UpperCamelCase = sequence_ids.index(self.pad_token_id ) else: UpperCamelCase = len(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_SCREAMING_SNAKE_CASE , top_spans=_SCREAMING_SNAKE_CASE , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_SCREAMING_SNAKE_CASE , start_index=_SCREAMING_SNAKE_CASE , end_index=_SCREAMING_SNAKE_CASE , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_SCREAMING_SNAKE_CASE ) >= num_spans: break return nbest_spans_predictions[:num_spans] def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> List[DPRSpanPrediction]: """simple docstring""" UpperCamelCase = [] for start_index, start_score in enumerate(_SCREAMING_SNAKE_CASE ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) UpperCamelCase = sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x[1] , reverse=_SCREAMING_SNAKE_CASE ) UpperCamelCase = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F"Wrong span indices: [{start_index}:{end_index}]" ) UpperCamelCase = end_index - start_index + 1 if length > max_answer_length: raise ValueError(F"Span is too long: {length} > {max_answer_length}" ) if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_SCREAMING_SNAKE_CASE ) == top_spans: break return chosen_span_intervals @add_end_docstrings(lowerCamelCase ) class a_ ( lowerCamelCase , lowerCamelCase ): lowercase = VOCAB_FILES_NAMES lowercase = READER_PRETRAINED_VOCAB_FILES_MAP lowercase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = READER_PRETRAINED_INIT_CONFIGURATION lowercase = ["""input_ids""", """attention_mask"""]
712
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand() def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand(args.accelerate_config_file ) class a_ ( lowerCamelCase ): @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = parser.add_parser("""env""" ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) download_parser.add_argument( """--accelerate-config_file""" , default=_SCREAMING_SNAKE_CASE , help="""The accelerate config file to use for the default values in the launching script.""" , ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def __init__( self , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = accelerate_config_file def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = """not installed""" if is_safetensors_available(): import safetensors UpperCamelCase = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors UpperCamelCase = F"{safetensors.__version__} but is ignored because of PyTorch version too old." UpperCamelCase = """not installed""" UpperCamelCase = UpperCamelCase = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file UpperCamelCase = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_SCREAMING_SNAKE_CASE ): UpperCamelCase = load_config_from_file(self._accelerate_config_file ).to_dict() UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else F"\t{accelerate_config}" ) UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_torch_available(): import torch UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_tf_available(): import tensorflow as tf UpperCamelCase = tf.__version__ try: # deprecated in v2.1 UpperCamelCase = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool UpperCamelCase = bool(tf.config.list_physical_devices("""GPU""" ) ) UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_flax_available(): import flax import jax import jaxlib UpperCamelCase = flax.__version__ UpperCamelCase = jax.__version__ UpperCamelCase = jaxlib.__version__ UpperCamelCase = jax.lib.xla_bridge.get_backend().platform UpperCamelCase = { """`transformers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Huggingface_hub version""": huggingface_hub.__version__, """Safetensors version""": F"{safetensors_version}", """Accelerate version""": F"{accelerate_version}", """Accelerate config""": F"{accelerate_config_str}", """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """Tensorflow version (GPU?)""": F"{tf_version} ({tf_cuda_available})", """Flax version (CPU?/GPU?/TPU?)""": F"{flax_version} ({jax_backend})", """Jax version""": F"{jax_version}", """JaxLib version""": F"{jaxlib_version}", """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(_SCREAMING_SNAKE_CASE ) ) return info @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
35
0
'''simple docstring''' import fire from utils import calculate_rouge, save_json def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , **__UpperCamelCase )-> int: UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()] UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()][: len(__UpperCamelCase )] UpperCamelCase = calculate_rouge(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) if save_path is not None: save_json(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
713
'''simple docstring''' from math import factorial def lowercase__ ( __UpperCamelCase = 20 )-> int: UpperCamelCase = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCamelCase = n // 2 return int(factorial(__UpperCamelCase ) / (factorial(__UpperCamelCase ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: SCREAMING_SNAKE_CASE__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
35
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} SCREAMING_SNAKE_CASE__ = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE__ = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } SCREAMING_SNAKE_CASE__ = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class a_ ( lowerCamelCase ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = PRETRAINED_INIT_CONFIGURATION lowercase = ["""input_ids""", """attention_mask"""] lowercase = DistilBertTokenizer def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> int: """simple docstring""" super().__init__( _SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , do_lower_case=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , tokenize_chinese_chars=_SCREAMING_SNAKE_CASE , strip_accents=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , _SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get("""strip_accents""" , _SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , _SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): UpperCamelCase = getattr(_SCREAMING_SNAKE_CASE , normalizer_state.pop("""type""" ) ) UpperCamelCase = do_lower_case UpperCamelCase = strip_accents UpperCamelCase = tokenize_chinese_chars UpperCamelCase = normalizer_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = do_lower_case def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: """simple docstring""" UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]: """simple docstring""" UpperCamelCase = [self.sep_token_id] UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple[str]: """simple docstring""" UpperCamelCase = self._tokenizer.model.save(_SCREAMING_SNAKE_CASE , name=_SCREAMING_SNAKE_CASE ) return tuple(_SCREAMING_SNAKE_CASE )
714
'''simple docstring''' from math import sqrt def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = 0 for i in range(1 , int(sqrt(__UpperCamelCase ) + 1 ) ): if n % i == 0 and i != sqrt(__UpperCamelCase ): total += i + n // i elif i == sqrt(__UpperCamelCase ): total += i return total - n def lowercase__ ( __UpperCamelCase = 10000 )-> int: UpperCamelCase = sum( i for i in range(1 , __UpperCamelCase ) if sum_of_divisors(sum_of_divisors(__UpperCamelCase ) ) == i and sum_of_divisors(__UpperCamelCase ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
35
0
'''simple docstring''' import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {'vocab_file': 'vocab.txt', 'emoji_file': 'emoji.json'} SCREAMING_SNAKE_CASE__ = { 'vocab_file': { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt', }, 'emoji_file': { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json', }, } SCREAMING_SNAKE_CASE__ = { 'abeja/gpt-neox-japanese-2.7b': 2_0_4_8, } def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> int: with open(__UpperCamelCase , """r""" , encoding="""utf-8""" ) as f: UpperCamelCase = json.loads(f.read() ) UpperCamelCase = collections.OrderedDict() UpperCamelCase = collections.OrderedDict() UpperCamelCase = collections.OrderedDict() with open(__UpperCamelCase , """r""" , encoding="""utf-8""" ) as f: UpperCamelCase = f.readlines() UpperCamelCase = [[t.rstrip("""\n""" )] if (t == """,""" or """,""" not in t) else t.rstrip("""\n""" ).split(""",""" ) for t in token] for idx, b in enumerate(__UpperCamelCase ): UpperCamelCase = b UpperCamelCase = idx for wd in b: UpperCamelCase = idx return vocab, raw_vocab, ids_to_tokens, emoji class a_ ( lowerCamelCase ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = ["""input_ids""", """attention_mask"""] def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="<|endoftext|>" , _SCREAMING_SNAKE_CASE="<|endoftext|>" , _SCREAMING_SNAKE_CASE="<|startoftext|>" , _SCREAMING_SNAKE_CASE="<|endoftext|>" , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" super().__init__( unk_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , do_clean_text=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) if not os.path.isfile(_SCREAMING_SNAKE_CASE ): raise ValueError( F"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained" """ model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`""" ) if not os.path.isfile(_SCREAMING_SNAKE_CASE ): raise ValueError( F"Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google" """ pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`""" ) UpperCamelCase = do_clean_text UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = load_vocab_and_emoji(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji ) @property def A__ ( self ) -> List[str]: """simple docstring""" return len(self.raw_vocab ) def A__ ( self ) -> Any: """simple docstring""" return dict(self.raw_vocab , **self.added_tokens_encoder ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self.subword_tokenizer.tokenize(_SCREAMING_SNAKE_CASE , clean=self.do_clean_text ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" return self.vocab.get(_SCREAMING_SNAKE_CASE , self.vocab.get(self.unk_token ) ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return self.subword_tokenizer.convert_id_to_token(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = """""".join(_SCREAMING_SNAKE_CASE ).strip() return out_string def A__ ( self , _SCREAMING_SNAKE_CASE ) -> List[int]: """simple docstring""" UpperCamelCase = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) + [self.eos_token_id] ) if len(_SCREAMING_SNAKE_CASE ) > self.model_max_length: UpperCamelCase = input_ids[-self.model_max_length :] return input_ids def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple[str]: """simple docstring""" UpperCamelCase = 0 if os.path.isdir(_SCREAMING_SNAKE_CASE ): UpperCamelCase = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""emoji_file"""] ) else: UpperCamelCase = ( (filename_prefix + """-""" if filename_prefix else """""") + save_directory + VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase = ( (filename_prefix + """-""" if filename_prefix else """""") + save_directory + VOCAB_FILES_NAMES["""emoji_file"""] ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." """ Please check that the vocabulary is not corrupted!""" ) UpperCamelCase = token_index writer.write(""",""".join(_SCREAMING_SNAKE_CASE ) + """\n""" ) index += 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as writer: json.dump(self.emoji , _SCREAMING_SNAKE_CASE ) return vocab_file, emoji_file class a_ ( lowerCamelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase = vocab # same as swe UpperCamelCase = ids_to_tokens # same as bpe UpperCamelCase = emoji UpperCamelCase = np.max([len(_SCREAMING_SNAKE_CASE ) for w in self.vocab.keys()] ) UpperCamelCase = re.compile(R"""(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)""" ) UpperCamelCase = re.compile(R"""[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*""" ) UpperCamelCase = re.compile(R"""[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}""" ) UpperCamelCase = re.compile( R"""([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*""" ) UpperCamelCase = re.compile( R"""(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*""" ) UpperCamelCase = re.compile( R"""((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*""" ) UpperCamelCase = """─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿""" UpperCamelCase = """▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟""" UpperCamelCase = str.maketrans({k: """<BLOCK>""" for k in keisen + blocks} ) def __len__( self ) -> List[Any]: """simple docstring""" return len(self.ids_to_tokens ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = self.content_repattera.sub("""<URL>""" , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self.content_repattera.sub("""<EMAIL>""" , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self.content_repattera.sub("""<TEL>""" , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self.content_repattera.sub("""<DATE>""" , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self.content_repattera.sub("""<DATE>""" , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self.content_repattera.sub("""<PRICE>""" , _SCREAMING_SNAKE_CASE ) UpperCamelCase = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: UpperCamelCase = content.replace("""<BLOCK><BLOCK>""" , """<BLOCK>""" ) return content def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" UpperCamelCase = text.replace(""" """ , """<SP>""" ) UpperCamelCase = text.replace(""" """ , """<SP>""" ) UpperCamelCase = text.replace("""\r\n""" , """<BR>""" ) UpperCamelCase = text.replace("""\n""" , """<BR>""" ) UpperCamelCase = text.replace("""\r""" , """<BR>""" ) UpperCamelCase = text.replace("""\t""" , """<TAB>""" ) UpperCamelCase = text.replace("""—""" , """ー""" ) UpperCamelCase = text.replace("""−""" , """ー""" ) for k, v in self.emoji["emoji"].items(): if k in text: UpperCamelCase = text.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if clean: UpperCamelCase = self.clean_text(_SCREAMING_SNAKE_CASE ) def check_simbol(_SCREAMING_SNAKE_CASE ): UpperCamelCase = x.encode() if len(_SCREAMING_SNAKE_CASE ) == 1 and len(_SCREAMING_SNAKE_CASE ) == 2: UpperCamelCase = (int(e[0] ) << 8) + int(e[1] ) if ( (c >= 0xC2_A1 and c <= 0xC2_BF) or (c >= 0xC7_80 and c <= 0xC7_83) or (c >= 0xCA_B9 and c <= 0xCB_BF) or (c >= 0xCC_80 and c <= 0xCD_A2) ): return True return False def checkuae(_SCREAMING_SNAKE_CASE ): UpperCamelCase = x.encode() if len(_SCREAMING_SNAKE_CASE ) == 1 and len(_SCREAMING_SNAKE_CASE ) == 3: UpperCamelCase = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0xE2_80_80 and c <= 0xE2_B0_7F: return True return False UpperCamelCase = 0 UpperCamelCase = [] while pos < len(_SCREAMING_SNAKE_CASE ): UpperCamelCase = min(len(_SCREAMING_SNAKE_CASE ) , pos + self.maxlen + 1 ) if text[pos] == """<""" else pos + 3 UpperCamelCase = [] # (token_id, token, pos) for e in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , -1 ): UpperCamelCase = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(_SCREAMING_SNAKE_CASE ) > 2: UpperCamelCase = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(_SCREAMING_SNAKE_CASE ) > 0: # the smallest token_id is adopted UpperCamelCase ,UpperCamelCase ,UpperCamelCase = sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x[0] )[0] result.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase = e else: UpperCamelCase = pos + 1 UpperCamelCase = text[pos:end] if check_simbol(_SCREAMING_SNAKE_CASE ): result.append("""<KIGOU>""" ) elif checkuae(_SCREAMING_SNAKE_CASE ): result.append("""<U2000U2BFF>""" ) else: for i in wd.encode("""utf-8""" ): result.append("""<|byte%d|>""" % i ) UpperCamelCase = end return result def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="\n" ) -> List[Any]: """simple docstring""" UpperCamelCase = [] UpperCamelCase = [] UpperCamelCase = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(_SCREAMING_SNAKE_CASE ) > 0: words.append(bytearray(_SCREAMING_SNAKE_CASE ).decode("""utf-8""" , errors="""replace""" ) ) UpperCamelCase = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji["""emoji_inv"""][word] ) elif word == "<SP>": words.append(""" """ ) elif word == "<BR>": words.append(_SCREAMING_SNAKE_CASE ) elif word == "<TAB>": words.append("""\t""" ) elif word == "<BLOCK>": words.append("""▀""" ) elif word == "<KIGOU>": words.append("""ǀ""" ) elif word == "<U2000U2BFF>": words.append("""‖""" ) else: words.append(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: words.append(bytearray(_SCREAMING_SNAKE_CASE ).decode("""utf-8""" , errors="""replace""" ) ) UpperCamelCase = """""".join(_SCREAMING_SNAKE_CASE ) return text
715
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 16_00, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 16_00, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class a_ ( unittest.TestCase ): def A__ ( self ) -> Dict: """simple docstring""" if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() , encoding="""utf-8""" , check=_SCREAMING_SNAKE_CASE , ) assert hasattr(self , """env""" ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = { """enabled""": True, """processes_per_host""": 8, } UpperCamelCase = { """enabled""": True, """parameters""": { """microbatches""": 4, """placement_strategy""": """spread""", """pipeline""": """interleaved""", """optimize""": """speed""", """partitions""": 4, """ddp""": True, }, } UpperCamelCase = {"""smdistributed""": {"""modelparallel""": smp_options}, """mpi""": mpi_options} UpperCamelCase = """trainer""" if self.script == """run_glue.py""" else """smtrainer""" # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" , instance_count=_SCREAMING_SNAKE_CASE , instance_type=self.instance_type , debugger_hook_config=_SCREAMING_SNAKE_CASE , hyperparameters={ **self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path, """max_steps""": 500, } , metric_definitions=self.env.metric_definitions , distribution=_SCREAMING_SNAKE_CASE , py_version="""py36""" , ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" TrainingJobAnalytics(_SCREAMING_SNAKE_CASE ).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv" ) @parameterized.expand([(1,)] ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = self.create_estimator(_SCREAMING_SNAKE_CASE ) # run training estimator.fit() # result dataframe UpperCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis UpperCamelCase = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""] ) UpperCamelCase = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping UpperCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get("""TrainingTimeInSeconds""" , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy ) assert all(t <= self.results["""eval_loss"""] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" , """w""" ) as outfile: json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} , _SCREAMING_SNAKE_CASE )
716
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> str: if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase = """""" while len(__UpperCamelCase ) % 3 != 0: UpperCamelCase = """0""" + bin_string UpperCamelCase = [ bin_string[index : index + 3] for index in range(len(__UpperCamelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase = 0 for index, val in enumerate(__UpperCamelCase ): oct_val += int(2 ** (2 - index) * int(__UpperCamelCase ) ) oct_string += str(__UpperCamelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' SCREAMING_SNAKE_CASE__ = 6_5_5_2_1 def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = 1 UpperCamelCase = 0 for plain_chr in plain_text: UpperCamelCase = (a + ord(__UpperCamelCase )) % MOD_ADLER UpperCamelCase = (b + a) % MOD_ADLER return (b << 16) | a
717
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowercase__ ( __UpperCamelCase=None )-> Union[str, Any]: if subparsers is not None: UpperCamelCase = subparsers.add_parser("""env""" ) else: UpperCamelCase = argparse.ArgumentParser("""Accelerate env command""" ) parser.add_argument( """--config_file""" , default=__UpperCamelCase , help="""The config file to use for the default values in the launching script.""" ) if subparsers is not None: parser.set_defaults(func=__UpperCamelCase ) return parser def lowercase__ ( __UpperCamelCase )-> List[str]: UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = is_xpu_available() UpperCamelCase = is_npu_available() UpperCamelCase = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(__UpperCamelCase ): UpperCamelCase = load_config_from_file(args.config_file ).to_dict() UpperCamelCase = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """PyTorch XPU available""": str(__UpperCamelCase ), """PyTorch NPU available""": str(__UpperCamelCase ), """System RAM""": F"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", } if pt_cuda_available: UpperCamelCase = torch.cuda.get_device_name() print("""\nCopy-and-paste the text below in your GitHub issue\n""" ) print("""\n""".join([F"- {prop}: {val}" for prop, val in info.items()] ) ) print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" ) UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else F"\t{accelerate_config}" ) print(__UpperCamelCase ) UpperCamelCase = accelerate_config return info def lowercase__ ( )-> int: UpperCamelCase = env_command_parser() UpperCamelCase = parser.parse_args() env_command(__UpperCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
35
0
'''simple docstring''' import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class a_ ( lowerCamelCase ): lowercase = (DDIMParallelScheduler,) lowercase = (("""eta""", 0.0), ("""num_inference_steps""", 50)) def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = { """num_train_timesteps""": 1000, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """clip_sample""": True, } config.update(**_SCREAMING_SNAKE_CASE ) return config def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase ,UpperCamelCase = 10, 0.0 UpperCamelCase = self.dummy_model() UpperCamelCase = self.dummy_sample_deter scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ) for t in scheduler.timesteps: UpperCamelCase = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).prev_sample return sample def A__ ( self ) -> Union[str, Any]: """simple docstring""" for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[str]: """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config(steps_offset=1 ) UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def A__ ( self ) -> Any: """simple docstring""" for beta_start, beta_end in zip([0.0_0_0_1, 0.0_0_1, 0.0_1, 0.1] , [0.0_0_2, 0.0_2, 0.2, 2] ): self.check_over_configs(beta_start=_SCREAMING_SNAKE_CASE , beta_end=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[int]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Dict: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" self.check_over_configs(thresholding=_SCREAMING_SNAKE_CASE ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=_SCREAMING_SNAKE_CASE , prediction_type=_SCREAMING_SNAKE_CASE , sample_max_value=_SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config() UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.1_4_7_7_1 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.3_2_4_6_0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.0_0_9_7_9 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.0_2 ) ) < 1e-5 def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.scheduler_classes[0] UpperCamelCase = self.get_scheduler_config() UpperCamelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase ,UpperCamelCase = 10, 0.0 scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.dummy_model() UpperCamelCase = self.dummy_sample_deter UpperCamelCase = self.dummy_sample_deter + 0.1 UpperCamelCase = self.dummy_sample_deter - 0.1 UpperCamelCase = samplea.shape[0] UpperCamelCase = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCamelCase = torch.arange(_SCREAMING_SNAKE_CASE )[0:3, None].repeat(1 , _SCREAMING_SNAKE_CASE ) UpperCamelCase = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCamelCase = scheduler.batch_step_no_noise(_SCREAMING_SNAKE_CASE , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.4_9_8_2 ) < 1e-3 def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.full_loop() UpperCamelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.2_2_3_9_6_7 ) < 1e-3 def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = self.full_loop(prediction_type="""v_prediction""" ) UpperCamelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 52.5302 ) < 1e-2 assert abs(result_mean.item() - 0.0_6_8_4 ) < 1e-3 def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.full_loop(set_alpha_to_one=_SCREAMING_SNAKE_CASE , beta_start=0.0_1 ) UpperCamelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.1_9_5_1 ) < 1e-3 def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.full_loop(set_alpha_to_one=_SCREAMING_SNAKE_CASE , beta_start=0.0_1 ) UpperCamelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.1_9_4_1 ) < 1e-3
718
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) UpperCamelCase = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__UpperCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
35
0
import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Union[str, Any]: # Initialise PyTorch model UpperCamelCase = LxmertConfig.from_json_file(__UpperCamelCase ) print(F"Building PyTorch model from configuration: {config}" ) UpperCamelCase = LxmertForPreTraining(__UpperCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , __UpperCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
719
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowercase__ ( __UpperCamelCase , __UpperCamelCase=1 )-> Tuple: if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> Dict: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item.replace("""in_layers.0""" , """norm1""" ) UpperCamelCase = new_item.replace("""in_layers.2""" , """conv1""" ) UpperCamelCase = new_item.replace("""out_layers.0""" , """norm2""" ) UpperCamelCase = new_item.replace("""out_layers.3""" , """conv2""" ) UpperCamelCase = new_item.replace("""emb_layers.1""" , """time_emb_proj""" ) UpperCamelCase = new_item.replace("""skip_connection""" , """conv_shortcut""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> List[str]: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item UpperCamelCase = new_item.replace("""norm.weight""" , """group_norm.weight""" ) UpperCamelCase = new_item.replace("""norm.bias""" , """group_norm.bias""" ) UpperCamelCase = new_item.replace("""proj_out.weight""" , """proj_attn.weight""" ) UpperCamelCase = new_item.replace("""proj_out.bias""" , """proj_attn.bias""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None )-> str: assert isinstance(__UpperCamelCase , __UpperCamelCase ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): UpperCamelCase = old_checkpoint[path] UpperCamelCase = old_tensor.shape[0] // 3 UpperCamelCase = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) UpperCamelCase = old_tensor.shape[0] // config["""num_head_channels"""] // 3 UpperCamelCase = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = old_tensor.split(channels // num_heads , dim=1 ) UpperCamelCase = query.reshape(__UpperCamelCase ) UpperCamelCase = key.reshape(__UpperCamelCase ) UpperCamelCase = value.reshape(__UpperCamelCase ) for path in paths: UpperCamelCase = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here UpperCamelCase = new_path.replace("""middle_block.0""" , """mid_block.resnets.0""" ) UpperCamelCase = new_path.replace("""middle_block.1""" , """mid_block.attentions.0""" ) UpperCamelCase = new_path.replace("""middle_block.2""" , """mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: UpperCamelCase = new_path.replace(replacement["""old"""] , replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: UpperCamelCase = old_checkpoint[path["""old"""]][:, :, 0] else: UpperCamelCase = old_checkpoint[path["""old"""]] def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = {} UpperCamelCase = checkpoint["""time_embed.0.weight"""] UpperCamelCase = checkpoint["""time_embed.0.bias"""] UpperCamelCase = checkpoint["""time_embed.2.weight"""] UpperCamelCase = checkpoint["""time_embed.2.bias"""] UpperCamelCase = checkpoint["""input_blocks.0.0.weight"""] UpperCamelCase = checkpoint["""input_blocks.0.0.bias"""] UpperCamelCase = checkpoint["""out.0.weight"""] UpperCamelCase = checkpoint["""out.0.bias"""] UpperCamelCase = checkpoint["""out.2.weight"""] UpperCamelCase = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"input_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the middle blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"middle_block.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the output blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"output_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } for i in range(1 , __UpperCamelCase ): UpperCamelCase = (i - 1) // (config["""num_res_blocks"""] + 1) UpperCamelCase = (i - 1) % (config["""num_res_blocks"""] + 1) UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.0" in key] UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.1" in key] if F"input_blocks.{i}.0.op.weight" in checkpoint: UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.weight" ] UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.bias" ] continue UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"input_blocks.{i}.0", """new""": F"down_blocks.{block_id}.resnets.{layer_in_block_id}"} UpperCamelCase = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path, resnet_op] , config=__UpperCamelCase ) if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"input_blocks.{i}.1", """new""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"input_blocks.{i}.1.qkv.bias": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"input_blocks.{i}.1.qkv.weight": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase , ) UpperCamelCase = middle_blocks[0] UpperCamelCase = middle_blocks[1] UpperCamelCase = middle_blocks[2] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase ) for i in range(__UpperCamelCase ): UpperCamelCase = i // (config["""num_res_blocks"""] + 1) UpperCamelCase = i % (config["""num_res_blocks"""] + 1) UpperCamelCase = [shave_segments(__UpperCamelCase , 2 ) for name in output_blocks[i]] UpperCamelCase = {} for layer in output_block_layers: UpperCamelCase ,UpperCamelCase = layer.split(""".""" )[0], shave_segments(__UpperCamelCase , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__UpperCamelCase ) else: UpperCamelCase = [layer_name] if len(__UpperCamelCase ) > 1: UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.0" in key] UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.1" in key] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"output_blocks.{i}.0", """new""": F"up_blocks.{block_id}.resnets.{layer_in_block_id}"} assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , config=__UpperCamelCase ) if ["conv.weight", "conv.bias"] in output_block_list.values(): UpperCamelCase = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.weight" ] UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.bias" ] # Clear attentions as they have been attributed above. if len(__UpperCamelCase ) == 2: UpperCamelCase = [] if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"output_blocks.{i}.1", """new""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"output_blocks.{i}.1.qkv.bias": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"output_blocks.{i}.1.qkv.weight": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None , config=__UpperCamelCase , ) else: UpperCamelCase = renew_resnet_paths(__UpperCamelCase , n_shave_prefix_segments=1 ) for path in resnet_0_paths: UpperCamelCase = """.""".join(["""output_blocks""", str(__UpperCamelCase ), path["""old"""]] ) UpperCamelCase = """.""".join(["""up_blocks""", str(__UpperCamelCase ), """resnets""", str(__UpperCamelCase ), path["""new"""]] ) UpperCamelCase = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = torch.load(args.checkpoint_path) with open(args.config_file) as f: SCREAMING_SNAKE_CASE__ = json.loads(f.read()) SCREAMING_SNAKE_CASE__ = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] SCREAMING_SNAKE_CASE__ = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: SCREAMING_SNAKE_CASE__ = DDPMScheduler.from_config('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = VQModel.from_pretrained('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
35
0
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester 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 SCREAMING_SNAKE_CASE__ = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class a_ : lowercase = PegasusConfig lowercase = {} lowercase = """gelu""" def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=20 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , ) -> int: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = eos_token_id UpperCamelCase = pad_token_id UpperCamelCase = bos_token_id def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) UpperCamelCase = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase = np.concatenate([input_ids, eos_tensor] , axis=1 ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = self.config_cls( 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_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) UpperCamelCase = prepare_pegasus_inputs_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return config, inputs_dict def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase = 20 UpperCamelCase = model_class_name(_SCREAMING_SNAKE_CASE ) UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase ,UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , _SCREAMING_SNAKE_CASE , decoder_attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , decoder_position_ids=_SCREAMING_SNAKE_CASE , ) UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , _SCREAMING_SNAKE_CASE , decoder_attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_SCREAMING_SNAKE_CASE , ) UpperCamelCase = model.decode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"Max diff is {diff}" ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = 20 UpperCamelCase = model_class_name(_SCREAMING_SNAKE_CASE ) UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) UpperCamelCase ,UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) UpperCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , _SCREAMING_SNAKE_CASE , decoder_attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE , decoder_position_ids=_SCREAMING_SNAKE_CASE , ) UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , _SCREAMING_SNAKE_CASE , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_SCREAMING_SNAKE_CASE , decoder_position_ids=_SCREAMING_SNAKE_CASE , ) UpperCamelCase = model.decode(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , decoder_attention_mask=_SCREAMING_SNAKE_CASE ) UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"Max diff is {diff}" ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None , )-> Tuple: if attention_mask is None: UpperCamelCase = np.not_equal(__UpperCamelCase , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: UpperCamelCase = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class a_ ( lowerCamelCase , unittest.TestCase ): lowercase = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) lowercase = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () lowercase = True lowercase = False lowercase = False lowercase = False def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = FlaxPegasusModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) @jax.jit def encode_jitted(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ): return model.encode(input_ids=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) with self.subTest("""JIT Enabled""" ): UpperCamelCase = encode_jitted(**_SCREAMING_SNAKE_CASE ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase = encode_jitted(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for jitted_output, output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertEqual(jitted_output.shape , output.shape ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) UpperCamelCase = { """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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return model.decode( decoder_input_ids=_SCREAMING_SNAKE_CASE , decoder_attention_mask=_SCREAMING_SNAKE_CASE , encoder_outputs=_SCREAMING_SNAKE_CASE , ) with self.subTest("""JIT Enabled""" ): UpperCamelCase = decode_jitted(**_SCREAMING_SNAKE_CASE ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): UpperCamelCase = decode_jitted(**_SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for jitted_output, output in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertEqual(jitted_output.shape , output.shape ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" for model_class_name in self.all_model_classes: UpperCamelCase = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=_SCREAMING_SNAKE_CASE ) UpperCamelCase = np.ones((1, 1) ) UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @slow def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) UpperCamelCase = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) UpperCamelCase = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] UpperCamelCase = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] UpperCamelCase = tokenizer(_SCREAMING_SNAKE_CASE , return_tensors="""np""" , truncation=_SCREAMING_SNAKE_CASE , max_length=512 , padding=_SCREAMING_SNAKE_CASE ) UpperCamelCase = model.generate(**_SCREAMING_SNAKE_CASE , num_beams=2 ).sequences UpperCamelCase = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) assert tgt_text == decoded
720
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowercase__ ( __UpperCamelCase )-> float: return np.dot(__UpperCamelCase , __UpperCamelCase ) class a_ : def __init__( self , *, _SCREAMING_SNAKE_CASE = np.inf , _SCREAMING_SNAKE_CASE = "linear" , _SCREAMING_SNAKE_CASE = 0.0 , ) -> None: """simple docstring""" UpperCamelCase = regularization UpperCamelCase = gamma if kernel == "linear": UpperCamelCase = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("""rbf kernel requires gamma""" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("""gamma must be float or int""" ) if not self.gamma > 0: raise ValueError("""gamma must be > 0""" ) UpperCamelCase = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCamelCase = F"Unknown kernel: {kernel}" raise ValueError(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: """simple docstring""" return np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float: """simple docstring""" return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = observations UpperCamelCase = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCamelCase) ,) = np.shape(_SCREAMING_SNAKE_CASE ) def to_minimize(_SCREAMING_SNAKE_CASE ) -> float: UpperCamelCase = 0 ((UpperCamelCase) ,) = np.shape(_SCREAMING_SNAKE_CASE ) for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(_SCREAMING_SNAKE_CASE ) UpperCamelCase = LinearConstraint(_SCREAMING_SNAKE_CASE , 0 , 0 ) UpperCamelCase = Bounds(0 , self.regularization ) UpperCamelCase = minimize( _SCREAMING_SNAKE_CASE , np.ones(_SCREAMING_SNAKE_CASE ) , bounds=_SCREAMING_SNAKE_CASE , constraints=[ly_contraint] ).x UpperCamelCase = l_star # calculating mean offset of separation plane to points UpperCamelCase = 0 for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCamelCase = s / n def A__ ( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , _SCREAMING_SNAKE_CASE ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
721
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration SCREAMING_SNAKE_CASE__ = 'facebook/wmt19-en-de' SCREAMING_SNAKE_CASE__ = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model SCREAMING_SNAKE_CASE__ = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) SCREAMING_SNAKE_CASE__ = FSMTForConditionalGeneration(config) print(f'num of params {tiny_model.num_parameters()}') # Test SCREAMING_SNAKE_CASE__ = tokenizer(['Making tiny model'], return_tensors='pt') SCREAMING_SNAKE_CASE__ = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save SCREAMING_SNAKE_CASE__ = 'tiny-wmt19-en-de' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f'Generated {mname_tiny}') # Upload # transformers-cli upload tiny-wmt19-en-de
35
0
'''simple docstring''' import collections import os import re from pathlib import Path __a = 'src/transformers' # Matches is_xxx_available() __a = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} __a = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] __a = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available __a = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") __a = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] __a = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", __a = re.compile(R'^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], __a = re.compile(R'^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo __a = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: __a = re.compile(R'^\s*try:') # Catches a line with else: __a = re.compile(R'^\s*else:') def lowercase__ ( __UpperCamelCase )-> Union[str, Any]: if _re_test_backend.search(__UpperCamelCase ) is None: return None UpperCamelCase = [b[0] for b in _re_backend.findall(__UpperCamelCase )] backends.sort() return "_and_".join(__UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> List[str]: with open(__UpperCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: UpperCamelCase = f.readlines() UpperCamelCase = 0 while line_index < len(__UpperCamelCase ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(__UpperCamelCase ): return None # First grab the objects without a specific backend in _import_structure UpperCamelCase = [] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: UpperCamelCase = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(__UpperCamelCase ): UpperCamelCase = _re_one_line_import_struct.search(__UpperCamelCase ).groups()[0] UpperCamelCase = re.findall(R"""\[([^\]]+)\]""" , __UpperCamelCase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue UpperCamelCase = _re_import_struct_key_value.search(__UpperCamelCase ) if single_line_import_search is not None: UpperCamelCase = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(__UpperCamelCase ) > 0] objects.extend(__UpperCamelCase ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 UpperCamelCase = {"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. UpperCamelCase = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCamelCase = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCamelCase = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): UpperCamelCase = lines[line_index] if _re_import_struct_add_one.search(__UpperCamelCase ) is not None: objects.append(_re_import_struct_add_one.search(__UpperCamelCase ).groups()[0] ) elif _re_import_struct_add_many.search(__UpperCamelCase ) is not None: UpperCamelCase = _re_import_struct_add_many.search(__UpperCamelCase ).groups()[0].split(""", """ ) UpperCamelCase = [obj[1:-1] for obj in imports if len(__UpperCamelCase ) > 0] objects.extend(__UpperCamelCase ) elif _re_between_brackets.search(__UpperCamelCase ) is not None: UpperCamelCase = _re_between_brackets.search(__UpperCamelCase ).groups()[0].split(""", """ ) UpperCamelCase = [obj[1:-1] for obj in imports if len(__UpperCamelCase ) > 0] objects.extend(__UpperCamelCase ) elif _re_quote_object.search(__UpperCamelCase ) is not None: objects.append(_re_quote_object.search(__UpperCamelCase ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 12 + """\"""" ): objects.append(line[13:-3] ) line_index += 1 UpperCamelCase = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend UpperCamelCase = [] while ( line_index < len(__UpperCamelCase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): UpperCamelCase = lines[line_index] UpperCamelCase = _re_import.search(__UpperCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 UpperCamelCase = {"""none""": objects} # Let's continue with backend-specific objects while line_index < len(__UpperCamelCase ): # If the line is an if is_backend_available, we grab all objects associated. UpperCamelCase = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCamelCase = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCamelCase = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): UpperCamelCase = lines[line_index] UpperCamelCase = _re_import.search(__UpperCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 12 ): objects.append(line[12:-2] ) line_index += 1 UpperCamelCase = objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List[str]: def find_duplicates(__UpperCamelCase ): return [k for k, v in collections.Counter(__UpperCamelCase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] UpperCamelCase = [] for key in import_dict_objects.keys(): UpperCamelCase = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F"Duplicate _import_structure definitions for: {duplicate_imports}" ) UpperCamelCase = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): UpperCamelCase = """base imports""" if key == """none""" else F"{key} backend" errors.append(F"Differences for {name}:" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F" {a} in TYPE_HINT but not in _import_structure." ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F" {a} in _import_structure but not in TYPE_HINT." ) return errors def lowercase__ ( )-> Optional[int]: UpperCamelCase = [] for root, _, files in os.walk(__UpperCamelCase ): if "__init__.py" in files: UpperCamelCase = os.path.join(__UpperCamelCase , """__init__.py""" ) UpperCamelCase = parse_init(__UpperCamelCase ) if objects is not None: UpperCamelCase = analyze_results(*__UpperCamelCase ) if len(__UpperCamelCase ) > 0: UpperCamelCase = F"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" failures.append("""\n""".join(__UpperCamelCase ) ) if len(__UpperCamelCase ) > 0: raise ValueError("""\n\n""".join(__UpperCamelCase ) ) def lowercase__ ( )-> int: UpperCamelCase = [] for path, directories, files in os.walk(__UpperCamelCase ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(__UpperCamelCase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(__UpperCamelCase ) / folder).glob("""*.py""" ) ) ) == 0: continue UpperCamelCase = str((Path(__UpperCamelCase ) / folder).relative_to(__UpperCamelCase ) ) UpperCamelCase = short_path.replace(os.path.sep , """.""" ) submodules.append(__UpperCamelCase ) for fname in files: if fname == "__init__.py": continue UpperCamelCase = str((Path(__UpperCamelCase ) / fname).relative_to(__UpperCamelCase ) ) UpperCamelCase = short_path.replace(""".py""" , """""" ).replace(os.path.sep , """.""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(__UpperCamelCase ) return submodules __a = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', 'models.esm.openfold_utils', ] def lowercase__ ( )-> int: # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import UpperCamelCase = direct_transformers_import(__UpperCamelCase ) UpperCamelCase = set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(__UpperCamelCase , """__init__.py""" ) , """r""" ) as f: UpperCamelCase = f.read() import_structure_keys.update(set(re.findall(R"""import_structure\[\"([^\"]*)\"\]""" , __UpperCamelCase ) ) ) UpperCamelCase = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(__UpperCamelCase ) > 0: UpperCamelCase = """\n""".join(F"- {module}" for module in module_not_registered ) raise ValueError( """The following submodules are not properly registed in the main init of Transformers:\n""" F"{list_of_modules}\n" """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
700
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) SCREAMING_SNAKE_CASE__ = CLIPImageProcessor() SCREAMING_SNAKE_CASE__ = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') SCREAMING_SNAKE_CASE__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
35
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class a_ ( lowerCamelCase ): lowercase = 42 lowercase = 42 class a_ ( nn.Module ): lowercase = 42 lowercase = (16, 32, 96, 2_56) lowercase = jnp.floataa def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCamelCase = [] for i in range(len(self.block_out_channels ) - 1 ): UpperCamelCase = self.block_out_channels[i] UpperCamelCase = self.block_out_channels[i + 1] UpperCamelCase = nn.Conv( _SCREAMING_SNAKE_CASE , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase = nn.Conv( _SCREAMING_SNAKE_CASE , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase = blocks UpperCamelCase = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.conv_in(_SCREAMING_SNAKE_CASE ) UpperCamelCase = nn.silu(_SCREAMING_SNAKE_CASE ) for block in self.blocks: UpperCamelCase = block(_SCREAMING_SNAKE_CASE ) UpperCamelCase = nn.silu(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.conv_out(_SCREAMING_SNAKE_CASE ) return embedding @flax_register_to_config class a_ ( nn.Module , lowerCamelCase , lowerCamelCase ): lowercase = 32 lowercase = 4 lowercase = ( """CrossAttnDownBlock2D""", """CrossAttnDownBlock2D""", """CrossAttnDownBlock2D""", """DownBlock2D""", ) lowercase = False lowercase = (3_20, 6_40, 12_80, 12_80) lowercase = 2 lowercase = 8 lowercase = None lowercase = 12_80 lowercase = 0.0 lowercase = False lowercase = jnp.floataa lowercase = True lowercase = 0 lowercase = """rgb""" lowercase = (16, 32, 96, 2_56) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> FrozenDict: """simple docstring""" UpperCamelCase = (1, self.in_channels, self.sample_size, self.sample_size) UpperCamelCase = jnp.zeros(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) UpperCamelCase = jnp.ones((1,) , dtype=jnp.intaa ) UpperCamelCase = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) UpperCamelCase = (1, 3, self.sample_size * 8, self.sample_size * 8) UpperCamelCase = jnp.zeros(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) UpperCamelCase ,UpperCamelCase = jax.random.split(_SCREAMING_SNAKE_CASE ) UpperCamelCase = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )["params"] def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = self.block_out_channels UpperCamelCase = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. UpperCamelCase = self.num_attention_heads or self.attention_head_dim # input UpperCamelCase = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time UpperCamelCase = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) UpperCamelCase = FlaxTimestepEmbedding(_SCREAMING_SNAKE_CASE , dtype=self.dtype ) UpperCamelCase = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) UpperCamelCase = self.only_cross_attention if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = (num_attention_heads,) * len(self.down_block_types ) # down UpperCamelCase = [] UpperCamelCase = [] UpperCamelCase = block_out_channels[0] UpperCamelCase = nn.Conv( _SCREAMING_SNAKE_CASE , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_SCREAMING_SNAKE_CASE ) for i, down_block_type in enumerate(self.down_block_types ): UpperCamelCase = output_channel UpperCamelCase = block_out_channels[i] UpperCamelCase = i == len(_SCREAMING_SNAKE_CASE ) - 1 if down_block_type == "CrossAttnDownBlock2D": UpperCamelCase = FlaxCrossAttnDownBlockaD( in_channels=_SCREAMING_SNAKE_CASE , out_channels=_SCREAMING_SNAKE_CASE , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: UpperCamelCase = FlaxDownBlockaD( in_channels=_SCREAMING_SNAKE_CASE , out_channels=_SCREAMING_SNAKE_CASE , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_SCREAMING_SNAKE_CASE ) for _ in range(self.layers_per_block ): UpperCamelCase = nn.Conv( _SCREAMING_SNAKE_CASE , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_SCREAMING_SNAKE_CASE ) if not is_final_block: UpperCamelCase = nn.Conv( _SCREAMING_SNAKE_CASE , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(_SCREAMING_SNAKE_CASE ) UpperCamelCase = down_blocks UpperCamelCase = controlnet_down_blocks # mid UpperCamelCase = block_out_channels[-1] UpperCamelCase = FlaxUNetMidBlockaDCrossAttn( in_channels=_SCREAMING_SNAKE_CASE , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) UpperCamelCase = nn.Conv( _SCREAMING_SNAKE_CASE , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 1.0 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = False , ) -> Union[FlaxControlNetOutput, Tuple]: """simple docstring""" UpperCamelCase = self.controlnet_conditioning_channel_order if channel_order == "bgr": UpperCamelCase = jnp.flip(_SCREAMING_SNAKE_CASE , axis=1 ) # 1. time if not isinstance(_SCREAMING_SNAKE_CASE , jnp.ndarray ): UpperCamelCase = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_SCREAMING_SNAKE_CASE , jnp.ndarray ) and len(timesteps.shape ) == 0: UpperCamelCase = timesteps.astype(dtype=jnp.floataa ) UpperCamelCase = jnp.expand_dims(_SCREAMING_SNAKE_CASE , 0 ) UpperCamelCase = self.time_proj(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.time_embedding(_SCREAMING_SNAKE_CASE ) # 2. pre-process UpperCamelCase = jnp.transpose(_SCREAMING_SNAKE_CASE , (0, 2, 3, 1) ) UpperCamelCase = self.conv_in(_SCREAMING_SNAKE_CASE ) UpperCamelCase = jnp.transpose(_SCREAMING_SNAKE_CASE , (0, 2, 3, 1) ) UpperCamelCase = self.controlnet_cond_embedding(_SCREAMING_SNAKE_CASE ) sample += controlnet_cond # 3. down UpperCamelCase = (sample,) for down_block in self.down_blocks: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase ,UpperCamelCase = down_block(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , deterministic=not train ) else: UpperCamelCase ,UpperCamelCase = down_block(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , deterministic=not train ) down_block_res_samples += res_samples # 4. mid UpperCamelCase = self.mid_block(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , deterministic=not train ) # 5. contronet blocks UpperCamelCase = () for down_block_res_sample, controlnet_block in zip(_SCREAMING_SNAKE_CASE , self.controlnet_down_blocks ): UpperCamelCase = controlnet_block(_SCREAMING_SNAKE_CASE ) controlnet_down_block_res_samples += (down_block_res_sample,) UpperCamelCase = controlnet_down_block_res_samples UpperCamelCase = self.controlnet_mid_block(_SCREAMING_SNAKE_CASE ) # 6. scaling UpperCamelCase = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=_SCREAMING_SNAKE_CASE , mid_block_res_sample=_SCREAMING_SNAKE_CASE )
701
'''simple docstring''' from __future__ import annotations from typing import Any class a_ : def __init__( self , _SCREAMING_SNAKE_CASE = 6 ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None self.create_linked_list(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = current_node UpperCamelCase = current_node for _ in range(1 , _SCREAMING_SNAKE_CASE ): UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = previous_node UpperCamelCase = current_node UpperCamelCase = self.front UpperCamelCase = previous_node def A__ ( self ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCamelCase = self.rear.next if self.rear: UpperCamelCase = data def A__ ( self ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCamelCase = self.front.data UpperCamelCase = None return data UpperCamelCase = self.front UpperCamelCase = old_front.next UpperCamelCase = old_front.data UpperCamelCase = None return data def A__ ( self ) -> None: """simple docstring""" if self.is_empty(): raise Exception("""Empty Queue""" ) def A__ ( self ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class a_ : def __init__( self ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' from math import isclose, sqrt def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> tuple[float, float, float]: UpperCamelCase = point_y / 4 / point_x UpperCamelCase = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) UpperCamelCase = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) UpperCamelCase = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 UpperCamelCase = outgoing_gradient**2 + 4 UpperCamelCase = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) UpperCamelCase = (point_y - outgoing_gradient * point_x) ** 2 - 100 UpperCamelCase = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) UpperCamelCase = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point UpperCamelCase = x_minus if isclose(__UpperCamelCase , __UpperCamelCase ) else x_plus UpperCamelCase = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def lowercase__ ( __UpperCamelCase = 1.4 , __UpperCamelCase = -9.6 )-> int: UpperCamelCase = 0 UpperCamelCase = first_x_coord UpperCamelCase = first_y_coord UpperCamelCase = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): UpperCamelCase ,UpperCamelCase ,UpperCamelCase = next_point(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'{solution() = }')
702
'''simple docstring''' import fire from utils import calculate_rouge, save_json def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , **__UpperCamelCase )-> int: UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()] UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()][: len(__UpperCamelCase )] UpperCamelCase = calculate_rouge(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) if save_path is not None: save_json(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
35
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class a_ ( lowerCamelCase , unittest.TestCase ): lowercase = KandinskyImgaImgPipeline lowercase = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] lowercase = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] lowercase = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] lowercase = False @property def A__ ( self ) -> str: """simple docstring""" return 32 @property def A__ ( self ) -> Dict: """simple docstring""" return 32 @property def A__ ( self ) -> Union[str, Any]: """simple docstring""" return self.time_input_dim @property def A__ ( self ) -> Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def A__ ( self ) -> Union[str, Any]: """simple docstring""" return 100 @property def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def A__ ( self ) -> Any: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) UpperCamelCase = MultilingualCLIP(_SCREAMING_SNAKE_CASE ) UpperCamelCase = text_encoder.eval() return text_encoder @property def A__ ( self ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } UpperCamelCase = UNetaDConditionModel(**_SCREAMING_SNAKE_CASE ) return model @property def A__ ( self ) -> Tuple: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def A__ ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = VQModel(**self.dummy_movq_kwargs ) return model def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.dummy_text_encoder UpperCamelCase = self.dummy_tokenizer UpperCamelCase = self.dummy_unet UpperCamelCase = self.dummy_movq UpperCamelCase = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } UpperCamelCase = DDIMScheduler(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> int: """simple docstring""" UpperCamelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_SCREAMING_SNAKE_CASE ) # create init_image UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase = Image.fromarray(np.uinta(_SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((256, 256) ) if str(_SCREAMING_SNAKE_CASE ).startswith("""mps""" ): UpperCamelCase = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: UpperCamelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) UpperCamelCase = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def A__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = """cpu""" UpperCamelCase = self.get_dummy_components() UpperCamelCase = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = output.images UpperCamelCase = pipe( **self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) , return_dict=_SCREAMING_SNAKE_CASE , )[0] UpperCamelCase = image[0, -3:, -3:, -1] UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class a_ ( unittest.TestCase ): def A__ ( self ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) UpperCamelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) UpperCamelCase = """A red cartoon frog, 4k""" UpperCamelCase = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) UpperCamelCase = pipeline.to(_SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) UpperCamelCase ,UpperCamelCase = pipe_prior( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() UpperCamelCase = pipeline( _SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , image_embeds=_SCREAMING_SNAKE_CASE , negative_image_embeds=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
703
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> tuple[float, list[float]]: UpperCamelCase = list(range(len(__UpperCamelCase ) ) ) UpperCamelCase = [v / w for v, w in zip(__UpperCamelCase , __UpperCamelCase )] index.sort(key=lambda __UpperCamelCase : ratio[i] , reverse=__UpperCamelCase ) UpperCamelCase = 0 UpperCamelCase = [0] * len(__UpperCamelCase ) for i in index: if weight[i] <= capacity: UpperCamelCase = 1 max_value += value[i] capacity -= weight[i] else: UpperCamelCase = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> list: UpperCamelCase = len(__UpperCamelCase ) UpperCamelCase = [] for i in range(len(__UpperCamelCase ) - pat_len + 1 ): UpperCamelCase = True for j in range(__UpperCamelCase ): if s[i + j] != pattern[j]: UpperCamelCase = False break if match_found: position.append(__UpperCamelCase ) return position if __name__ == "__main__": assert naive_pattern_search('ABCDEFG', 'DE') == [3] print(naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC'))
704
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a_ ( lowerCamelCase ): lowercase = """deformable_detr""" lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # deformable attributes UpperCamelCase = num_feature_levels UpperCamelCase = encoder_n_points UpperCamelCase = decoder_n_points UpperCamelCase = two_stage UpperCamelCase = two_stage_num_proposals UpperCamelCase = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient UpperCamelCase = focal_alpha UpperCamelCase = disable_custom_kernels super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A__ ( self ) -> int: """simple docstring""" return self.d_model def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output
35
0
'''simple docstring''' import random def lowercase__ ( __UpperCamelCase )-> bool: UpperCamelCase = num - 1 UpperCamelCase = 0 while s % 2 == 0: UpperCamelCase = s // 2 t += 1 for _ in range(5 ): UpperCamelCase = random.randrange(2 , num - 1 ) UpperCamelCase = pow(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) if v != 1: UpperCamelCase = 0 while v != (num - 1): if i == t - 1: return False else: UpperCamelCase = i + 1 UpperCamelCase = (v**2) % num return True def lowercase__ ( __UpperCamelCase )-> bool: if num < 2: return False UpperCamelCase = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__UpperCamelCase ) def lowercase__ ( __UpperCamelCase = 1024 )-> int: while True: UpperCamelCase = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(__UpperCamelCase ): return num if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = generate_large_prime() print(('Prime number:', num)) print(('is_prime_low_num:', is_prime_low_num(num)))
705
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowercase__ ( __UpperCamelCase )-> Any: UpperCamelCase = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase ,UpperCamelCase = emb.weight.shape UpperCamelCase = nn.Linear(__UpperCamelCase , __UpperCamelCase , bias=__UpperCamelCase ) UpperCamelCase = emb.weight.data return lin_layer def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase = torch.load(__UpperCamelCase , map_location="""cpu""" ) UpperCamelCase = mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""] UpperCamelCase = mam_aaa["""model"""] remove_ignore_keys_(__UpperCamelCase ) UpperCamelCase = state_dict["""encoder.embed_tokens.weight"""].shape[0] UpperCamelCase = MaMaaaConfig( vocab_size=__UpperCamelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , ) UpperCamelCase = state_dict["""decoder.embed_tokens.weight"""] UpperCamelCase = MaMaaaForConditionalGeneration(__UpperCamelCase ) model.model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) UpperCamelCase = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
35
0
'''simple docstring''' from __future__ import annotations from typing import Any class a_ : def __init__( self , _SCREAMING_SNAKE_CASE = 6 ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None self.create_linked_list(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = current_node UpperCamelCase = current_node for _ in range(1 , _SCREAMING_SNAKE_CASE ): UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = previous_node UpperCamelCase = current_node UpperCamelCase = self.front UpperCamelCase = previous_node def A__ ( self ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCamelCase = self.rear.next if self.rear: UpperCamelCase = data def A__ ( self ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCamelCase = self.front.data UpperCamelCase = None return data UpperCamelCase = self.front UpperCamelCase = old_front.next UpperCamelCase = old_front.data UpperCamelCase = None return data def A__ ( self ) -> None: """simple docstring""" if self.is_empty(): raise Exception("""Empty Queue""" ) def A__ ( self ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class a_ : def __init__( self ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if __name__ == "__main__": import doctest doctest.testmod()
706
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class a_ ( lowerCamelCase ): def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """tf_padding""" ) ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """depth_multiplier""" ) ) class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE="relu6" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=None , ) -> List[str]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = depth_multiplier UpperCamelCase = min_depth UpperCamelCase = tf_padding UpperCamelCase = int(last_hidden_size * depth_multiplier ) UpperCamelCase = output_stride UpperCamelCase = hidden_act UpperCamelCase = classifier_dropout_prob UpperCamelCase = use_labels UpperCamelCase = is_training UpperCamelCase = num_labels UpperCamelCase = initializer_range UpperCamelCase = scope def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels, pixel_labels def A__ ( self ) -> Optional[Any]: """simple docstring""" return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = MobileNetVaForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowercase = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModelTester(self ) UpperCamelCase = MobileNetVaConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not output attentions""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = 26 self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def A__ ( self ) -> Dict: """simple docstring""" for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = MobileNetVaModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowercase__ ( )-> Optional[Any]: UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def A__ ( self ) -> Dict: """simple docstring""" return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224""" ) if is_vision_available() else None ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224""" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits UpperCamelCase = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
35
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE__ = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
707
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-1' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-2' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-3' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-4' class a_ ( lowerCamelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , ) -> Any: """simple docstring""" super()._init_() UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline( vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , requires_safety_checker=_SCREAMING_SNAKE_CASE , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def A__ ( self ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , _SCREAMING_SNAKE_CASE ) for k in self.config.keys() if not k.startswith("""_""" )} def A__ ( self , _SCREAMING_SNAKE_CASE = "auto" ) -> Optional[Any]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" self.enable_attention_slicing(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" UpperCamelCase = """cuda""" if torch.cuda.is_available() else """cpu""" self.to(_SCREAMING_SNAKE_CASE ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
35
0
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class a_ ( unittest.TestCase ): def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = 0 def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """preprocessor_config.json""" UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) ) UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """preprocessor_config.json""" UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) ) UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """preprocessor_config.json""" UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ).to_dict() config_dict.pop("""image_processor_type""" ) UpperCamelCase = CLIPImageProcessor(**_SCREAMING_SNAKE_CASE ) # save in new folder model_config.save_pretrained(_SCREAMING_SNAKE_CASE ) config.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ) # make sure private variable is not incorrectly saved UpperCamelCase = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """preprocessor_config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) , ) UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Dict: """simple docstring""" with self.assertRaisesRegex( _SCREAMING_SNAKE_CASE , """clip-base is not a local folder and is not a valid model identifier""" ): UpperCamelCase = AutoImageProcessor.from_pretrained("""clip-base""" ) def A__ ( self ) -> Dict: """simple docstring""" with self.assertRaisesRegex( _SCREAMING_SNAKE_CASE , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE , revision="""aaaaaa""" ) def A__ ( self ) -> int: """simple docstring""" with self.assertRaisesRegex( _SCREAMING_SNAKE_CASE , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): UpperCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model""" ) def A__ ( self ) -> str: """simple docstring""" with self.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_SCREAMING_SNAKE_CASE ) UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE , trust_remote_code=_SCREAMING_SNAKE_CASE ) self.assertEqual(reloaded_image_processor.__class__.__name__ , """NewImageProcessor""" ) def A__ ( self ) -> Tuple: """simple docstring""" try: AutoConfig.register("""custom""" , _SCREAMING_SNAKE_CASE ) AutoImageProcessor.register(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_SCREAMING_SNAKE_CASE ): AutoImageProcessor.register(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """preprocessor_config.json""" UpperCamelCase = Path(_SCREAMING_SNAKE_CASE ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_SCREAMING_SNAKE_CASE , """w""" ) ) UpperCamelCase = CustomImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def A__ ( self ) -> Union[str, Any]: """simple docstring""" class a_ ( lowerCamelCase ): lowercase = True try: AutoConfig.register("""custom""" , _SCREAMING_SNAKE_CASE ) AutoImageProcessor.register(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # If remote code is not set, the default is to use local UpperCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(not hasattr(_SCREAMING_SNAKE_CASE , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
708
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE__ = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if principal <= 0: raise Exception("""Principal borrowed must be > 0""" ) if rate_per_annum < 0: raise Exception("""Rate of interest must be >= 0""" ) if years_to_repay <= 0 or not isinstance(__UpperCamelCase , __UpperCamelCase ): raise Exception("""Years to repay must be an integer > 0""" ) # Yearly rate is divided by 12 to get monthly rate UpperCamelCase = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly UpperCamelCase = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
709
'''simple docstring''' SCREAMING_SNAKE_CASE__ = 8.31_44_62 # Unit - J mol-1 K-1 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = [1] UpperCamelCase ,UpperCamelCase ,UpperCamelCase = 0, 0, 0 UpperCamelCase = ugly_nums[ia] * 2 UpperCamelCase = ugly_nums[ia] * 3 UpperCamelCase = ugly_nums[ia] * 5 for _ in range(1 , __UpperCamelCase ): UpperCamelCase = min(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) ugly_nums.append(__UpperCamelCase ) if next_num == next_a: ia += 1 UpperCamelCase = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 UpperCamelCase = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 UpperCamelCase = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(f'{ugly_numbers(2_0_0) = }')
710
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__ = 1_6 SCREAMING_SNAKE_CASE__ = 3_2 def lowercase__ ( __UpperCamelCase , __UpperCamelCase = 16 )-> Dict: UpperCamelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__UpperCamelCase , max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__UpperCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase = 16 elif accelerator.mixed_precision != "no": UpperCamelCase = 8 else: UpperCamelCase = None return tokenizer.pad( __UpperCamelCase , padding="""longest""" , max_length=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. UpperCamelCase = DataLoader( tokenized_datasets["""train"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) UpperCamelCase = DataLoader( tokenized_datasets["""validation"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE__ = mocked_dataloaders # noqa: F811 def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List[Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __UpperCamelCase ) == "1": UpperCamelCase = 2 # New Code # UpperCamelCase = int(args.gradient_accumulation_steps ) UpperCamelCase = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__UpperCamelCase ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase = config["""lr"""] UpperCamelCase = int(config["""num_epochs"""] ) UpperCamelCase = int(config["""seed"""] ) UpperCamelCase = int(config["""batch_size"""] ) UpperCamelCase = evaluate.load("""glue""" , """mrpc""" ) set_seed(__UpperCamelCase ) UpperCamelCase ,UpperCamelCase = get_dataloaders(__UpperCamelCase , __UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase = AdamW(params=model.parameters() , lr=__UpperCamelCase ) # Instantiate scheduler UpperCamelCase = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase , num_warmup_steps=100 , num_training_steps=(len(__UpperCamelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = accelerator.prepare( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Now we train the model for epoch in range(__UpperCamelCase ): model.train() with LocalSGD( accelerator=__UpperCamelCase , model=__UpperCamelCase , local_sgd_steps=__UpperCamelCase , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__UpperCamelCase ): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = output.loss accelerator.backward(__UpperCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = outputs.logits.argmax(dim=-1 ) UpperCamelCase ,UpperCamelCase = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__UpperCamelCase , references=__UpperCamelCase , ) UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __UpperCamelCase ) def lowercase__ ( )-> List[Any]: UpperCamelCase = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__UpperCamelCase , default=__UpperCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__UpperCamelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument( """--local_sgd_steps""" , type=__UpperCamelCase , default=8 , help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) UpperCamelCase = parser.parse_args() UpperCamelCase = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
35
0
'''simple docstring''' import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def lowercase__ ( __UpperCamelCase )-> Optional[int]: UpperCamelCase = np.inf def set_batch_size(__UpperCamelCase ) -> None: nonlocal batch_size if isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = min(__UpperCamelCase , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = min(__UpperCamelCase , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(__UpperCamelCase , __UpperCamelCase ) and feature.dtype == "binary": UpperCamelCase = min(__UpperCamelCase , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(__UpperCamelCase , __UpperCamelCase ) return None if batch_size is np.inf else batch_size class a_ ( lowerCamelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__( _SCREAMING_SNAKE_CASE , split=_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE , streaming=_SCREAMING_SNAKE_CASE , num_proc=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase = path_or_paths if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else {self.split: path_or_paths} UpperCamelCase = _PACKAGED_DATASETS_MODULES["""parquet"""][1] UpperCamelCase = Parquet( cache_dir=_SCREAMING_SNAKE_CASE , data_files=_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , hash=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> Tuple: """simple docstring""" if self.streaming: UpperCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None self.builder.download_and_prepare( download_config=_SCREAMING_SNAKE_CASE , download_mode=_SCREAMING_SNAKE_CASE , verification_mode=_SCREAMING_SNAKE_CASE , base_path=_SCREAMING_SNAKE_CASE , num_proc=self.num_proc , ) UpperCamelCase = self.builder.as_dataset( split=self.split , verification_mode=_SCREAMING_SNAKE_CASE , in_memory=self.keep_in_memory ) return dataset class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = dataset UpperCamelCase = path_or_buf UpperCamelCase = batch_size or get_writer_batch_size(dataset.features ) UpperCamelCase = parquet_writer_kwargs def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with open(self.path_or_buf , """wb+""" ) as buffer: UpperCamelCase = self._write(file_obj=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , **self.parquet_writer_kwargs ) else: UpperCamelCase = self._write(file_obj=self.path_or_buf , batch_size=_SCREAMING_SNAKE_CASE , **self.parquet_writer_kwargs ) return written def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = 0 UpperCamelCase = parquet_writer_kwargs.pop("""path_or_buf""" , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self.dataset.features.arrow_schema UpperCamelCase = pq.ParquetWriter(_SCREAMING_SNAKE_CASE , schema=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) for offset in logging.tqdm( range(0 , len(self.dataset ) , _SCREAMING_SNAKE_CASE ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating parquet from Arrow format""" , ): UpperCamelCase = query_table( table=self.dataset._data , key=slice(_SCREAMING_SNAKE_CASE , offset + batch_size ) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(_SCREAMING_SNAKE_CASE ) written += batch.nbytes writer.close() return written
711
'''simple docstring''' import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> Any: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = embed_dim UpperCamelCase = depths 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 = patch_norm UpperCamelCase = layer_norm_eps UpperCamelCase = initializer_range UpperCamelCase = is_training UpperCamelCase = scope UpperCamelCase = use_labels UpperCamelCase = type_sequence_label_size UpperCamelCase = encoder_stride UpperCamelCase = out_features UpperCamelCase = out_indices def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = self.get_config() return config, pixel_values, labels def A__ ( self ) -> str: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) UpperCamelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = ["""stem"""] UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowercase = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {} lowercase = False lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with""" """ `nn.DataParallel`""" ) ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self ) -> Dict: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A__ ( self ) -> int: """simple docstring""" return def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip("""Swin does not use inputs_embeds""" ) def A__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip("""Swin does not support feedforward chunking""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" ) def A__ ( self ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = 3 UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> List[Any]: """simple docstring""" pass def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): UpperCamelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( """Tuple and dict output are not equal. Difference:""" F" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:" F" {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has" F" `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}." ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) @require_torch class a_ ( unittest.TestCase , lowerCamelCase ): lowercase = (MaskFormerSwinBackbone,) if is_torch_available() else () lowercase = MaskFormerSwinConfig def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = inputs_dict["""pixel_values"""].shape[0] for backbone_class in self.all_model_classes: UpperCamelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
35
0
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand() def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand(args.accelerate_config_file ) class a_ ( lowerCamelCase ): @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = parser.add_parser("""env""" ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) download_parser.add_argument( """--accelerate-config_file""" , default=_SCREAMING_SNAKE_CASE , help="""The accelerate config file to use for the default values in the launching script.""" , ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def __init__( self , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = accelerate_config_file def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = """not installed""" if is_safetensors_available(): import safetensors UpperCamelCase = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors UpperCamelCase = F"{safetensors.__version__} but is ignored because of PyTorch version too old." UpperCamelCase = """not installed""" UpperCamelCase = UpperCamelCase = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file UpperCamelCase = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_SCREAMING_SNAKE_CASE ): UpperCamelCase = load_config_from_file(self._accelerate_config_file ).to_dict() UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else F"\t{accelerate_config}" ) UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_torch_available(): import torch UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_tf_available(): import tensorflow as tf UpperCamelCase = tf.__version__ try: # deprecated in v2.1 UpperCamelCase = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool UpperCamelCase = bool(tf.config.list_physical_devices("""GPU""" ) ) UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_flax_available(): import flax import jax import jaxlib UpperCamelCase = flax.__version__ UpperCamelCase = jax.__version__ UpperCamelCase = jaxlib.__version__ UpperCamelCase = jax.lib.xla_bridge.get_backend().platform UpperCamelCase = { """`transformers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Huggingface_hub version""": huggingface_hub.__version__, """Safetensors version""": F"{safetensors_version}", """Accelerate version""": F"{accelerate_version}", """Accelerate config""": F"{accelerate_config_str}", """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """Tensorflow version (GPU?)""": F"{tf_version} ({tf_cuda_available})", """Flax version (CPU?/GPU?/TPU?)""": F"{flax_version} ({jax_backend})", """Jax version""": F"{jax_version}", """JaxLib version""": F"{jaxlib_version}", """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(_SCREAMING_SNAKE_CASE ) ) return info @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
712
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand() def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand(args.accelerate_config_file ) class a_ ( lowerCamelCase ): @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = parser.add_parser("""env""" ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) download_parser.add_argument( """--accelerate-config_file""" , default=_SCREAMING_SNAKE_CASE , help="""The accelerate config file to use for the default values in the launching script.""" , ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def __init__( self , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = accelerate_config_file def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = """not installed""" if is_safetensors_available(): import safetensors UpperCamelCase = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors UpperCamelCase = F"{safetensors.__version__} but is ignored because of PyTorch version too old." UpperCamelCase = """not installed""" UpperCamelCase = UpperCamelCase = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file UpperCamelCase = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_SCREAMING_SNAKE_CASE ): UpperCamelCase = load_config_from_file(self._accelerate_config_file ).to_dict() UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else F"\t{accelerate_config}" ) UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_torch_available(): import torch UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_tf_available(): import tensorflow as tf UpperCamelCase = tf.__version__ try: # deprecated in v2.1 UpperCamelCase = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool UpperCamelCase = bool(tf.config.list_physical_devices("""GPU""" ) ) UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_flax_available(): import flax import jax import jaxlib UpperCamelCase = flax.__version__ UpperCamelCase = jax.__version__ UpperCamelCase = jaxlib.__version__ UpperCamelCase = jax.lib.xla_bridge.get_backend().platform UpperCamelCase = { """`transformers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Huggingface_hub version""": huggingface_hub.__version__, """Safetensors version""": F"{safetensors_version}", """Accelerate version""": F"{accelerate_version}", """Accelerate config""": F"{accelerate_config_str}", """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """Tensorflow version (GPU?)""": F"{tf_version} ({tf_cuda_available})", """Flax version (CPU?/GPU?/TPU?)""": F"{flax_version} ({jax_backend})", """Jax version""": F"{jax_version}", """JaxLib version""": F"{jaxlib_version}", """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(_SCREAMING_SNAKE_CASE ) ) return info @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
35
0
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a_ ( lowerCamelCase , unittest.TestCase ): lowercase = LayoutLMTokenizer lowercase = LayoutLMTokenizerFast lowercase = True lowercase = True def A__ ( self ) -> Tuple: """simple docstring""" super().setUp() UpperCamelCase = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase = """UNwant\u00E9d,running""" UpperCamelCase = """unwanted, running""" return input_text, output_text def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.tokenizer_class(self.vocab_file ) UpperCamelCase = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_SCREAMING_SNAKE_CASE , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , [7, 4, 5, 10, 8, 9] ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" pass
713
'''simple docstring''' from math import factorial def lowercase__ ( __UpperCamelCase = 20 )-> int: UpperCamelCase = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCamelCase = n // 2 return int(factorial(__UpperCamelCase ) / (factorial(__UpperCamelCase ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: SCREAMING_SNAKE_CASE__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
35
0
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE__ = logging.getLogger() def lowercase__ ( )-> List[Any]: UpperCamelCase = argparse.ArgumentParser() parser.add_argument("""-f""" ) UpperCamelCase = parser.parse_args() return args.f def lowercase__ ( __UpperCamelCase )-> Tuple: UpperCamelCase = {} UpperCamelCase = os.path.join(__UpperCamelCase , """all_results.json""" ) if os.path.exists(__UpperCamelCase ): with open(__UpperCamelCase , """r""" ) as f: UpperCamelCase = json.load(__UpperCamelCase ) else: raise ValueError(F"can't find {path}" ) return results def lowercase__ ( )-> int: UpperCamelCase = torch.cuda.is_available() and torch_device == """cuda""" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class a_ ( lowerCamelCase ): @classmethod def A__ ( cls ) -> List[Any]: """simple docstring""" UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = os.path.join(cls.tmpdir , """default_config.yml""" ) write_basic_config(save_location=cls.configPath ) UpperCamelCase = ["""accelerate""", """launch""", """--config_file""", cls.configPath] @classmethod def A__ ( cls ) -> Optional[Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --seed=42\n --checkpointing_steps epoch\n --with_tracking\n ".split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """glue_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --block_size 128\n --per_device_train_batch_size 5\n --per_device_eval_batch_size 5\n --num_train_epochs 2\n --output_dir {tmp_dir}\n --checkpointing_steps epoch\n --with_tracking\n ".split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["""perplexity"""] , 100 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """clm_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --num_train_epochs=1\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertLess(result["""perplexity"""] , 42 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """mlm_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = 7 if get_gpu_count() > 1 else 2 UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.7_5 ) self.assertLess(result["""train_loss"""] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """ner_no_trainer""" ) ) ) @unittest.skip(reason="""Fix me @muellerzr""" ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --seed=42\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["""eval_f1"""] , 28 ) self.assertGreaterEqual(result["""eval_exact"""] , 28 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """qa_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/swag/sample.json\n --validation_file tests/fixtures/tests_samples/swag/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=20\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """swag_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_rouge1"""] , 10 ) self.assertGreaterEqual(result["""eval_rouge2"""] , 2 ) self.assertGreaterEqual(result["""eval_rougeL"""] , 7 ) self.assertGreaterEqual(result["""eval_rougeLsum"""] , 7 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """summarization_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n --model_name_or_path sshleifer/student_marian_en_ro_6_1\n --source_lang en\n --target_lang ro\n --train_file tests/fixtures/tests_samples/wmt16/sample.json\n --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --num_beams=6\n --learning_rate=3e-3\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --source_lang en_XX\n --target_lang ro_RO\n --checkpointing_steps epoch\n --with_tracking\n ".split() run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_bleu"""] , 30 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """translation_no_trainer""" ) ) ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = logging.StreamHandler(sys.stdout ) logger.addHandler(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n --dataset_name huggingface/semantic-segmentation-test-sample\n --output_dir {tmp_dir}\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n ".split() run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(result["""eval_overall_accuracy"""] , 0.1_0 ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.get_auto_remove_tmp_dir() UpperCamelCase = F"\n {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n --model_name_or_path google/vit-base-patch16-224-in21k\n --dataset_name hf-internal-testing/cats_vs_dogs_sample\n --learning_rate 1e-4\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 1\n --max_train_steps 2\n --train_val_split 0.1\n --seed 42\n --output_dir {tmp_dir}\n --with_tracking\n --checkpointing_steps 1\n ".split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) UpperCamelCase = get_results(_SCREAMING_SNAKE_CASE ) # The base model scores a 25% self.assertGreaterEqual(result["""eval_accuracy"""] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """step_1""" ) ) ) self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE , """image_classification_no_trainer""" ) ) )
714
'''simple docstring''' from math import sqrt def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = 0 for i in range(1 , int(sqrt(__UpperCamelCase ) + 1 ) ): if n % i == 0 and i != sqrt(__UpperCamelCase ): total += i + n // i elif i == sqrt(__UpperCamelCase ): total += i return total - n def lowercase__ ( __UpperCamelCase = 10000 )-> int: UpperCamelCase = sum( i for i in range(1 , __UpperCamelCase ) if sum_of_divisors(sum_of_divisors(__UpperCamelCase ) ) == i and sum_of_divisors(__UpperCamelCase ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
35
0
'''simple docstring''' import argparse import importlib from pathlib import Path # Test all the extensions added in the setup SCREAMING_SNAKE_CASE__ = [ 'kernels/rwkv/wkv_cuda.cu', 'kernels/rwkv/wkv_op.cpp', 'kernels/deformable_detr/ms_deform_attn.h', 'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh', 'models/graphormer/algos_graphormer.pyx', ] def lowercase__ ( __UpperCamelCase )-> Union[str, Any]: # Test all the extensions added in the setup for file in FILES_TO_FIND: if not (transformers_path / file).exists(): return False return True if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.') SCREAMING_SNAKE_CASE__ = parser.parse_args() if args.check_lib: SCREAMING_SNAKE_CASE__ = importlib.import_module('transformers') SCREAMING_SNAKE_CASE__ = Path(transformers_module.__file__).parent else: SCREAMING_SNAKE_CASE__ = Path.cwd() / 'build/lib/transformers' if not test_custom_files_are_present(transformers_path): raise ValueError('The built release does not contain the custom files. Fix this before going further!')
715
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , )-> float: UpperCamelCase = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("""All input parameters must be positive""" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("""Relative densities cannot be greater than one""" ) else: UpperCamelCase = 1 - (matter_density + radiation_density + dark_energy) UpperCamelCase = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) UpperCamelCase = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation SCREAMING_SNAKE_CASE__ = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
716
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> str: if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase = """""" while len(__UpperCamelCase ) % 3 != 0: UpperCamelCase = """0""" + bin_string UpperCamelCase = [ bin_string[index : index + 3] for index in range(len(__UpperCamelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase = 0 for index, val in enumerate(__UpperCamelCase ): oct_val += int(2 ** (2 - index) * int(__UpperCamelCase ) ) oct_string += str(__UpperCamelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def lowercase__ ( )-> Any: with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(__UpperCamelCase ): requests.request("""GET""" , """https://huggingface.co""" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("""GET""" , """https://huggingface.co""" , timeout=1.0 ) @pytest.mark.integration def lowercase__ ( )-> Optional[Any]: with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("""GET""" , """https://huggingface.co""" ) def lowercase__ ( )-> int: with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(__UpperCamelCase ): http_head("""https://huggingface.co""" )
717
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowercase__ ( __UpperCamelCase=None )-> Union[str, Any]: if subparsers is not None: UpperCamelCase = subparsers.add_parser("""env""" ) else: UpperCamelCase = argparse.ArgumentParser("""Accelerate env command""" ) parser.add_argument( """--config_file""" , default=__UpperCamelCase , help="""The config file to use for the default values in the launching script.""" ) if subparsers is not None: parser.set_defaults(func=__UpperCamelCase ) return parser def lowercase__ ( __UpperCamelCase )-> List[str]: UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = is_xpu_available() UpperCamelCase = is_npu_available() UpperCamelCase = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(__UpperCamelCase ): UpperCamelCase = load_config_from_file(args.config_file ).to_dict() UpperCamelCase = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """PyTorch XPU available""": str(__UpperCamelCase ), """PyTorch NPU available""": str(__UpperCamelCase ), """System RAM""": F"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", } if pt_cuda_available: UpperCamelCase = torch.cuda.get_device_name() print("""\nCopy-and-paste the text below in your GitHub issue\n""" ) print("""\n""".join([F"- {prop}: {val}" for prop, val in info.items()] ) ) print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" ) UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else F"\t{accelerate_config}" ) print(__UpperCamelCase ) UpperCamelCase = accelerate_config return info def lowercase__ ( )-> int: UpperCamelCase = env_command_parser() UpperCamelCase = parser.parse_args() env_command(__UpperCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
35
0
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class a_ : lowercase = 42 lowercase = None # Automatically constructed lowercase = """dict""" lowercase = None lowercase = field(default="""Translation""" , init=lowerCamelCase , repr=lowerCamelCase ) def __call__( self ) -> List[Any]: """simple docstring""" return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def A__ ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class a_ : lowercase = None lowercase = None lowercase = None # Automatically constructed lowercase = """dict""" lowercase = None lowercase = field(default="""TranslationVariableLanguages""" , init=lowerCamelCase , repr=lowerCamelCase ) def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = sorted(set(self.languages ) ) if self.languages else None UpperCamelCase = len(self.languages ) if self.languages else None def __call__( self ) -> List[Any]: """simple docstring""" return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase = set(self.languages ) if self.languages and set(_SCREAMING_SNAKE_CASE ) - lang_set: raise ValueError( F"Some languages in example ({', '.join(sorted(set(_SCREAMING_SNAKE_CASE ) - lang_set ) )}) are not in valid set ({', '.join(_SCREAMING_SNAKE_CASE )})." ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. UpperCamelCase = [] for lang, text in translation_dict.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. UpperCamelCase ,UpperCamelCase = zip(*sorted(_SCREAMING_SNAKE_CASE ) ) return {"language": languages, "translation": translations} def A__ ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
718
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) UpperCamelCase = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__UpperCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
35
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 SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { '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_ ( lowerCamelCase ): lowercase = """marian""" lowercase = ["""past_key_values"""] lowercase = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , _SCREAMING_SNAKE_CASE=58101 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=58100 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=58100 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" UpperCamelCase = vocab_size UpperCamelCase = decoder_vocab_size or vocab_size UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = encoder_layerdrop UpperCamelCase = decoder_layerdrop UpperCamelCase = use_cache UpperCamelCase = encoder_layers UpperCamelCase = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase = share_encoder_decoder_embeddings super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , is_encoder_decoder=_SCREAMING_SNAKE_CASE , decoder_start_token_id=_SCREAMING_SNAKE_CASE , forced_eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) class a_ ( lowerCamelCase ): @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def A__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: UpperCamelCase = {0: """batch"""} UpperCamelCase = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: UpperCamelCase = {0: """batch""", 1: """decoder_sequence"""} UpperCamelCase = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_SCREAMING_SNAKE_CASE , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: UpperCamelCase ,UpperCamelCase = self.num_layers for i in range(_SCREAMING_SNAKE_CASE ): UpperCamelCase = {0: """batch""", 2: """past_sequence + sequence"""} UpperCamelCase = {0: """batch""", 2: """past_sequence + sequence"""} else: UpperCamelCase = 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 A__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = super().outputs else: UpperCamelCase = super(_SCREAMING_SNAKE_CASE , self ).outputs if self.use_past: UpperCamelCase ,UpperCamelCase = self.num_layers for i in range(_SCREAMING_SNAKE_CASE ): UpperCamelCase = {0: """batch""", 2: """past_sequence + sequence"""} UpperCamelCase = {0: """batch""", 2: """past_sequence + sequence"""} return common_outputs def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase = self._generate_dummy_inputs_for_encoder_and_decoder( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Generate decoder inputs UpperCamelCase = seq_length if not self.use_past else 1 UpperCamelCase = self._generate_dummy_inputs_for_encoder_and_decoder( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} UpperCamelCase = dict(**_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch UpperCamelCase ,UpperCamelCase = common_inputs["""input_ids"""].shape UpperCamelCase = common_inputs["""decoder_input_ids"""].shape[1] UpperCamelCase ,UpperCamelCase = self.num_attention_heads UpperCamelCase = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase = decoder_seq_length + 3 UpperCamelCase = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase = torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCamelCase = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase ,UpperCamelCase = self.num_layers UpperCamelCase = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) - min_num_layers UpperCamelCase = """encoder""" if num_encoder_layers > num_decoder_layers else """decoder""" for _ in range(_SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append( ( torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), ) ) # TODO: test this. UpperCamelCase = encoder_shape if remaining_side_name == """encoder""" else decoder_shape for _ in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append((torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE )) ) return common_inputs def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase = self._generate_dummy_inputs_for_encoder_and_decoder( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch UpperCamelCase ,UpperCamelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values UpperCamelCase = seqlen + 2 UpperCamelCase ,UpperCamelCase = self.num_layers UpperCamelCase ,UpperCamelCase = self.num_attention_heads UpperCamelCase = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase = common_inputs["""attention_mask"""].dtype UpperCamelCase = torch.cat( [common_inputs["""attention_mask"""], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCamelCase = [ (torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE )) for _ in range(_SCREAMING_SNAKE_CASE ) ] return common_inputs def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: """simple docstring""" UpperCamelCase = compute_effective_axis_dimension( _SCREAMING_SNAKE_CASE , 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 UpperCamelCase = tokenizer.num_special_tokens_to_add(_SCREAMING_SNAKE_CASE ) UpperCamelCase = compute_effective_axis_dimension( _SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_SCREAMING_SNAKE_CASE ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase = [""" """.join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase = dict(tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) ) return common_inputs def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = self._generate_dummy_inputs_for_default_and_seqaseq_lm( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) else: UpperCamelCase = self._generate_dummy_inputs_for_causal_lm( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) return common_inputs def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: UpperCamelCase = super()._flatten_past_key_values_(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: UpperCamelCase = super(_SCREAMING_SNAKE_CASE , self )._flatten_past_key_values_( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> float: """simple docstring""" return 1e-4
719
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowercase__ ( __UpperCamelCase , __UpperCamelCase=1 )-> Tuple: if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> Dict: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item.replace("""in_layers.0""" , """norm1""" ) UpperCamelCase = new_item.replace("""in_layers.2""" , """conv1""" ) UpperCamelCase = new_item.replace("""out_layers.0""" , """norm2""" ) UpperCamelCase = new_item.replace("""out_layers.3""" , """conv2""" ) UpperCamelCase = new_item.replace("""emb_layers.1""" , """time_emb_proj""" ) UpperCamelCase = new_item.replace("""skip_connection""" , """conv_shortcut""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> List[str]: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item UpperCamelCase = new_item.replace("""norm.weight""" , """group_norm.weight""" ) UpperCamelCase = new_item.replace("""norm.bias""" , """group_norm.bias""" ) UpperCamelCase = new_item.replace("""proj_out.weight""" , """proj_attn.weight""" ) UpperCamelCase = new_item.replace("""proj_out.bias""" , """proj_attn.bias""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None )-> str: assert isinstance(__UpperCamelCase , __UpperCamelCase ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): UpperCamelCase = old_checkpoint[path] UpperCamelCase = old_tensor.shape[0] // 3 UpperCamelCase = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) UpperCamelCase = old_tensor.shape[0] // config["""num_head_channels"""] // 3 UpperCamelCase = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = old_tensor.split(channels // num_heads , dim=1 ) UpperCamelCase = query.reshape(__UpperCamelCase ) UpperCamelCase = key.reshape(__UpperCamelCase ) UpperCamelCase = value.reshape(__UpperCamelCase ) for path in paths: UpperCamelCase = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here UpperCamelCase = new_path.replace("""middle_block.0""" , """mid_block.resnets.0""" ) UpperCamelCase = new_path.replace("""middle_block.1""" , """mid_block.attentions.0""" ) UpperCamelCase = new_path.replace("""middle_block.2""" , """mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: UpperCamelCase = new_path.replace(replacement["""old"""] , replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: UpperCamelCase = old_checkpoint[path["""old"""]][:, :, 0] else: UpperCamelCase = old_checkpoint[path["""old"""]] def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = {} UpperCamelCase = checkpoint["""time_embed.0.weight"""] UpperCamelCase = checkpoint["""time_embed.0.bias"""] UpperCamelCase = checkpoint["""time_embed.2.weight"""] UpperCamelCase = checkpoint["""time_embed.2.bias"""] UpperCamelCase = checkpoint["""input_blocks.0.0.weight"""] UpperCamelCase = checkpoint["""input_blocks.0.0.bias"""] UpperCamelCase = checkpoint["""out.0.weight"""] UpperCamelCase = checkpoint["""out.0.bias"""] UpperCamelCase = checkpoint["""out.2.weight"""] UpperCamelCase = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"input_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the middle blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"middle_block.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the output blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"output_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } for i in range(1 , __UpperCamelCase ): UpperCamelCase = (i - 1) // (config["""num_res_blocks"""] + 1) UpperCamelCase = (i - 1) % (config["""num_res_blocks"""] + 1) UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.0" in key] UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.1" in key] if F"input_blocks.{i}.0.op.weight" in checkpoint: UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.weight" ] UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.bias" ] continue UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"input_blocks.{i}.0", """new""": F"down_blocks.{block_id}.resnets.{layer_in_block_id}"} UpperCamelCase = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path, resnet_op] , config=__UpperCamelCase ) if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"input_blocks.{i}.1", """new""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"input_blocks.{i}.1.qkv.bias": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"input_blocks.{i}.1.qkv.weight": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase , ) UpperCamelCase = middle_blocks[0] UpperCamelCase = middle_blocks[1] UpperCamelCase = middle_blocks[2] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase ) for i in range(__UpperCamelCase ): UpperCamelCase = i // (config["""num_res_blocks"""] + 1) UpperCamelCase = i % (config["""num_res_blocks"""] + 1) UpperCamelCase = [shave_segments(__UpperCamelCase , 2 ) for name in output_blocks[i]] UpperCamelCase = {} for layer in output_block_layers: UpperCamelCase ,UpperCamelCase = layer.split(""".""" )[0], shave_segments(__UpperCamelCase , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__UpperCamelCase ) else: UpperCamelCase = [layer_name] if len(__UpperCamelCase ) > 1: UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.0" in key] UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.1" in key] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"output_blocks.{i}.0", """new""": F"up_blocks.{block_id}.resnets.{layer_in_block_id}"} assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , config=__UpperCamelCase ) if ["conv.weight", "conv.bias"] in output_block_list.values(): UpperCamelCase = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.weight" ] UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.bias" ] # Clear attentions as they have been attributed above. if len(__UpperCamelCase ) == 2: UpperCamelCase = [] if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"output_blocks.{i}.1", """new""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"output_blocks.{i}.1.qkv.bias": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"output_blocks.{i}.1.qkv.weight": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None , config=__UpperCamelCase , ) else: UpperCamelCase = renew_resnet_paths(__UpperCamelCase , n_shave_prefix_segments=1 ) for path in resnet_0_paths: UpperCamelCase = """.""".join(["""output_blocks""", str(__UpperCamelCase ), path["""old"""]] ) UpperCamelCase = """.""".join(["""up_blocks""", str(__UpperCamelCase ), """resnets""", str(__UpperCamelCase ), path["""new"""]] ) UpperCamelCase = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = torch.load(args.checkpoint_path) with open(args.config_file) as f: SCREAMING_SNAKE_CASE__ = json.loads(f.read()) SCREAMING_SNAKE_CASE__ = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] SCREAMING_SNAKE_CASE__ = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: SCREAMING_SNAKE_CASE__ = DDPMScheduler.from_config('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = VQModel.from_pretrained('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
35
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class a_ ( lowerCamelCase ): lowercase = """big_bird""" def __init__( self , _SCREAMING_SNAKE_CASE=50358 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-12 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=66 , _SCREAMING_SNAKE_CASE="block_sparse" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> Optional[int]: """simple docstring""" super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , sep_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase = vocab_size UpperCamelCase = max_position_embeddings UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = initializer_range UpperCamelCase = type_vocab_size UpperCamelCase = layer_norm_eps UpperCamelCase = use_cache UpperCamelCase = rescale_embeddings UpperCamelCase = attention_type UpperCamelCase = use_bias UpperCamelCase = block_size UpperCamelCase = num_random_blocks UpperCamelCase = classifier_dropout class a_ ( lowerCamelCase ): @property def A__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
720
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
721
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration SCREAMING_SNAKE_CASE__ = 'facebook/wmt19-en-de' SCREAMING_SNAKE_CASE__ = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model SCREAMING_SNAKE_CASE__ = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) SCREAMING_SNAKE_CASE__ = FSMTForConditionalGeneration(config) print(f'num of params {tiny_model.num_parameters()}') # Test SCREAMING_SNAKE_CASE__ = tokenizer(['Making tiny model'], return_tensors='pt') SCREAMING_SNAKE_CASE__ = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save SCREAMING_SNAKE_CASE__ = 'tiny-wmt19-en-de' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f'Generated {mname_tiny}') # Upload # transformers-cli upload tiny-wmt19-en-de
35
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __a = logging.get_logger(__name__) __a = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a_ ( lowerCamelCase ): lowercase = """deformable_detr""" lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # deformable attributes UpperCamelCase = num_feature_levels UpperCamelCase = encoder_n_points UpperCamelCase = decoder_n_points UpperCamelCase = two_stage UpperCamelCase = two_stage_num_proposals UpperCamelCase = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient UpperCamelCase = focal_alpha UpperCamelCase = disable_custom_kernels super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A__ ( self ) -> int: """simple docstring""" return self.d_model def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output
700
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) SCREAMING_SNAKE_CASE__ = CLIPImageProcessor() SCREAMING_SNAKE_CASE__ = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') SCREAMING_SNAKE_CASE__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
35
0
'''simple docstring''' from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE__ = namedtuple('covid_data', 'cases deaths recovered') def lowercase__ ( __UpperCamelCase = "https://www.worldometers.info/coronavirus/" )-> covid_data: UpperCamelCase = """//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(__UpperCamelCase ).content ).xpath(__UpperCamelCase ) ) SCREAMING_SNAKE_CASE__ = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
701
'''simple docstring''' from __future__ import annotations from typing import Any class a_ : def __init__( self , _SCREAMING_SNAKE_CASE = 6 ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None self.create_linked_list(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = current_node UpperCamelCase = current_node for _ in range(1 , _SCREAMING_SNAKE_CASE ): UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = previous_node UpperCamelCase = current_node UpperCamelCase = self.front UpperCamelCase = previous_node def A__ ( self ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCamelCase = self.rear.next if self.rear: UpperCamelCase = data def A__ ( self ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCamelCase = self.front.data UpperCamelCase = None return data UpperCamelCase = self.front UpperCamelCase = old_front.next UpperCamelCase = old_front.data UpperCamelCase = None return data def A__ ( self ) -> None: """simple docstring""" if self.is_empty(): raise Exception("""Empty Queue""" ) def A__ ( self ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class a_ : def __init__( self ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'facebook/data2vec-vision-base-ft': ( 'https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json' ), } class a_ ( lowerCamelCase ): lowercase = """data2vec-vision""" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-12 , _SCREAMING_SNAKE_CASE=224 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[3, 5, 7, 11] , _SCREAMING_SNAKE_CASE=[1, 2, 3, 6] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.4 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=255 , **_SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = use_mask_token UpperCamelCase = use_absolute_position_embeddings UpperCamelCase = use_relative_position_bias UpperCamelCase = use_shared_relative_position_bias UpperCamelCase = layer_scale_init_value UpperCamelCase = drop_path_rate UpperCamelCase = use_mean_pooling # decode head attributes (semantic segmentation) UpperCamelCase = out_indices UpperCamelCase = pool_scales # auxiliary head attributes (semantic segmentation) UpperCamelCase = use_auxiliary_head UpperCamelCase = auxiliary_loss_weight UpperCamelCase = auxiliary_channels UpperCamelCase = auxiliary_num_convs UpperCamelCase = auxiliary_concat_input UpperCamelCase = semantic_loss_ignore_index class a_ ( lowerCamelCase ): lowercase = version.parse("""1.11""" ) @property def A__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def A__ ( self ) -> float: """simple docstring""" return 1e-4
702
'''simple docstring''' import fire from utils import calculate_rouge, save_json def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , **__UpperCamelCase )-> int: UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()] UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()][: len(__UpperCamelCase )] UpperCamelCase = calculate_rouge(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) if save_path is not None: save_json(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
35
0
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels SCREAMING_SNAKE_CASE__ = object() # For specifying empty leaf dict `{}` SCREAMING_SNAKE_CASE__ = object() def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(__UpperCamelCase ) - len(__UpperCamelCase ) + 1 ): UpperCamelCase = [x.match(__UpperCamelCase ) for x, y in zip(__UpperCamelCase , ks[i:] )] if matches and all(__UpperCamelCase ): return True return False def lowercase__ ( __UpperCamelCase )-> Tuple: def replace(__UpperCamelCase , __UpperCamelCase ): for rule, replacement in rules: if _match(__UpperCamelCase , __UpperCamelCase ): return replacement return val return replace def lowercase__ ( )-> Optional[int]: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""" , __UpperCamelCase )), (("transformer", "wte", "embedding"), P("""mp""" , __UpperCamelCase )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(__UpperCamelCase , """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""" , __UpperCamelCase )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(__UpperCamelCase , """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""" , __UpperCamelCase )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def lowercase__ ( __UpperCamelCase )-> List[Any]: UpperCamelCase = _get_partition_rules() UpperCamelCase = _replacement_rules(__UpperCamelCase ) UpperCamelCase = {k: _unmatched for k in flatten_dict(__UpperCamelCase )} UpperCamelCase = {k: replace(__UpperCamelCase , __UpperCamelCase ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(__UpperCamelCase ) )
703
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> tuple[float, list[float]]: UpperCamelCase = list(range(len(__UpperCamelCase ) ) ) UpperCamelCase = [v / w for v, w in zip(__UpperCamelCase , __UpperCamelCase )] index.sort(key=lambda __UpperCamelCase : ratio[i] , reverse=__UpperCamelCase ) UpperCamelCase = 0 UpperCamelCase = [0] * len(__UpperCamelCase ) for i in index: if weight[i] <= capacity: UpperCamelCase = 1 max_value += value[i] capacity -= weight[i] else: UpperCamelCase = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class a_ ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=4 , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_attention_mask UpperCamelCase = use_token_type_ids UpperCamelCase = use_labels UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range UpperCamelCase = num_choices def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = None if self.use_attention_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase = None if self.use_token_type_ids: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase = AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class a_ ( lowerCamelCase , unittest.TestCase ): lowercase = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = FlaxAlbertModelTester(self ) @slow def A__ ( self ) -> List[str]: """simple docstring""" for model_class_name in self.all_model_classes: UpperCamelCase = model_class_name.from_pretrained("""albert-base-v2""" ) UpperCamelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @require_flax class a_ ( unittest.TestCase ): @slow def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = FlaxAlbertModel.from_pretrained("""albert-base-v2""" ) UpperCamelCase = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) UpperCamelCase = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) UpperCamelCase = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE )[0] UpperCamelCase = (1, 11, 768) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase = np.array( [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
704
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a_ ( lowerCamelCase ): lowercase = """deformable_detr""" lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # deformable attributes UpperCamelCase = num_feature_levels UpperCamelCase = encoder_n_points UpperCamelCase = decoder_n_points UpperCamelCase = two_stage UpperCamelCase = two_stage_num_proposals UpperCamelCase = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient UpperCamelCase = focal_alpha UpperCamelCase = disable_custom_kernels super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A__ ( self ) -> int: """simple docstring""" return self.d_model def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output
35
0
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase ) class a_ ( lowerCamelCase ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowercase = field(default="""text-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) lowercase = Features({"""text""": Value("""string""" )} ) lowercase = Features({"""labels""": ClassLabel} ) lowercase = """text""" lowercase = """labels""" def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" if self.label_column not in features: raise ValueError(F"Column {self.label_column} is not present in features." ) if not isinstance(features[self.label_column] , _SCREAMING_SNAKE_CASE ): raise ValueError(F"Column {self.label_column} is not a ClassLabel." ) UpperCamelCase = copy.deepcopy(self ) UpperCamelCase = self.label_schema.copy() UpperCamelCase = features[self.label_column] UpperCamelCase = label_schema return task_template @property def A__ ( self ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
705
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowercase__ ( __UpperCamelCase )-> Any: UpperCamelCase = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase ,UpperCamelCase = emb.weight.shape UpperCamelCase = nn.Linear(__UpperCamelCase , __UpperCamelCase , bias=__UpperCamelCase ) UpperCamelCase = emb.weight.data return lin_layer def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase = torch.load(__UpperCamelCase , map_location="""cpu""" ) UpperCamelCase = mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""] UpperCamelCase = mam_aaa["""model"""] remove_ignore_keys_(__UpperCamelCase ) UpperCamelCase = state_dict["""encoder.embed_tokens.weight"""].shape[0] UpperCamelCase = MaMaaaConfig( vocab_size=__UpperCamelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , ) UpperCamelCase = state_dict["""decoder.embed_tokens.weight"""] UpperCamelCase = MaMaaaForConditionalGeneration(__UpperCamelCase ) model.model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) UpperCamelCase = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase = 100 )-> int: UpperCamelCase = (n * (n + 1) // 2) ** 2 UpperCamelCase = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f'{solution() = }')
706
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class a_ ( lowerCamelCase ): def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """tf_padding""" ) ) self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """depth_multiplier""" ) ) class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE="relu6" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=None , ) -> List[str]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = depth_multiplier UpperCamelCase = min_depth UpperCamelCase = tf_padding UpperCamelCase = int(last_hidden_size * depth_multiplier ) UpperCamelCase = output_stride UpperCamelCase = hidden_act UpperCamelCase = classifier_dropout_prob UpperCamelCase = use_labels UpperCamelCase = is_training UpperCamelCase = num_labels UpperCamelCase = initializer_range UpperCamelCase = scope def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels, pixel_labels def A__ ( self ) -> Optional[Any]: """simple docstring""" return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = MobileNetVaForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowercase = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MobileNetVaModelTester(self ) UpperCamelCase = MobileNetVaConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings""" ) def A__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not output attentions""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = 26 self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def A__ ( self ) -> Dict: """simple docstring""" for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = MobileNetVaModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowercase__ ( )-> Optional[Any]: UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def A__ ( self ) -> Dict: """simple docstring""" return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224""" ) if is_vision_available() else None ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224""" ).to(_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits UpperCamelCase = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) UpperCamelCase = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
35
0
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( lowerCamelCase ): def A__ ( self ) -> Optional[int]: """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 A__ ( self ) -> int: """simple docstring""" UpperCamelCase = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self._create_example_records() UpperCamelCase = Dataset.from_list(_SCREAMING_SNAKE_CASE ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(_SCREAMING_SNAKE_CASE ): self.assertDictEqual(_SCREAMING_SNAKE_CASE , example_records[i] ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self._create_example_records() UpperCamelCase = Dataset.from_list(_SCREAMING_SNAKE_CASE ) UpperCamelCase = 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 A__ ( self ) -> str: # checks what happens with missing columns """simple docstring""" UpperCamelCase = [{"""col_1""": 1}, {"""col_2""": """x"""}] UpperCamelCase = Dataset.from_list(_SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def A__ ( self ) -> Any: # checks if the type can be inferred from the second record """simple docstring""" UpperCamelCase = [{"""col_1""": []}, {"""col_1""": [1, 2]}] UpperCamelCase = Dataset.from_list(_SCREAMING_SNAKE_CASE ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = Dataset.from_list([] ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 0 ) self.assertListEqual(dset.column_names , [] )
707
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-1' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-2' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-3' SCREAMING_SNAKE_CASE__ = 'CompVis/stable-diffusion-v1-4' class a_ ( lowerCamelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , ) -> Any: """simple docstring""" super()._init_() UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ) UpperCamelCase = StableDiffusionPipeline( vae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , requires_safety_checker=_SCREAMING_SNAKE_CASE , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def A__ ( self ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , _SCREAMING_SNAKE_CASE ) for k in self.config.keys() if not k.startswith("""_""" )} def A__ ( self , _SCREAMING_SNAKE_CASE = "auto" ) -> Optional[Any]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Tuple: """simple docstring""" self.enable_attention_slicing(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" return self.pipea( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) @torch.no_grad() def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 512 , _SCREAMING_SNAKE_CASE = 50 , _SCREAMING_SNAKE_CASE = 7.5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" UpperCamelCase = """cuda""" if torch.cuda.is_available() else """cpu""" self.to(_SCREAMING_SNAKE_CASE ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCamelCase = self.textaimg_sda_a( prompt=_SCREAMING_SNAKE_CASE , height=_SCREAMING_SNAKE_CASE , width=_SCREAMING_SNAKE_CASE , num_inference_steps=_SCREAMING_SNAKE_CASE , guidance_scale=_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE , num_images_per_prompt=_SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , latents=_SCREAMING_SNAKE_CASE , output_type=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
35
0
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def lowercase__ ( __UpperCamelCase )-> Optional[Any]: return EnvironmentCommand() class a_ ( lowerCamelCase ): @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase = parser.add_parser("""env""" ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = huggingface_hub.__version__ UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_torch_available(): import torch UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = """not installed""" if is_transformers_available(): import transformers UpperCamelCase = transformers.__version__ UpperCamelCase = """not installed""" if is_accelerate_available(): import accelerate UpperCamelCase = accelerate.__version__ UpperCamelCase = """not installed""" if is_xformers_available(): import xformers UpperCamelCase = xformers.__version__ UpperCamelCase = { """`diffusers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """Huggingface_hub version""": hub_version, """Transformers version""": transformers_version, """Accelerate version""": accelerate_version, """xFormers version""": xformers_version, """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(_SCREAMING_SNAKE_CASE ) ) return info @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
708
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule SCREAMING_SNAKE_CASE__ = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def lowercase__ ( __UpperCamelCase )-> str: return 1 / (1 + np.exp(-z )) def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List[Any]: return (-y * np.log(__UpperCamelCase ) - (1 - y) * np.log(1 - h )).mean() def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> List[Any]: UpperCamelCase = np.dot(__UpperCamelCase , __UpperCamelCase ) return np.sum(y * scores - np.log(1 + np.exp(__UpperCamelCase ) ) ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=70000 )-> List[Any]: UpperCamelCase = np.zeros(x.shape[1] ) for iterations in range(__UpperCamelCase ): UpperCamelCase = np.dot(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase = sigmoid_function(__UpperCamelCase ) UpperCamelCase = np.dot(x.T , h - y ) / y.size UpperCamelCase = theta - alpha * gradient # updating the weights UpperCamelCase = np.dot(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase = sigmoid_function(__UpperCamelCase ) UpperCamelCase = cost_function(__UpperCamelCase , __UpperCamelCase ) if iterations % 100 == 0: print(F"loss: {j} \t" ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = datasets.load_iris() SCREAMING_SNAKE_CASE__ = iris.data[:, :2] SCREAMING_SNAKE_CASE__ = (iris.target != 0) * 1 SCREAMING_SNAKE_CASE__ = 0.1 SCREAMING_SNAKE_CASE__ = logistic_reg(alpha, x, y, max_iterations=7_0_0_0_0) print('theta: ', theta) # printing the theta i.e our weights vector def lowercase__ ( __UpperCamelCase )-> str: return sigmoid_function( np.dot(__UpperCamelCase , __UpperCamelCase ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(1_0, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='b', label='0') plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='r', label='1') ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) = (x[:, 0].min(), x[:, 0].max()) ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) = (x[:, 1].min(), x[:, 1].max()) ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) SCREAMING_SNAKE_CASE__ = np.c_[xxa.ravel(), xxa.ravel()] SCREAMING_SNAKE_CASE__ = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='black') plt.legend() plt.show()
709
'''simple docstring''' SCREAMING_SNAKE_CASE__ = 8.31_44_62 # Unit - J mol-1 K-1 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params SCREAMING_SNAKE_CASE__ = getLogger(__name__) SCREAMING_SNAKE_CASE__ = 'cuda' if torch.cuda.is_available() else 'cpu' def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 8 , __UpperCamelCase = DEFAULT_DEVICE , __UpperCamelCase=False , __UpperCamelCase="summarization" , __UpperCamelCase=None , **__UpperCamelCase , )-> Dict: UpperCamelCase = Path(__UpperCamelCase ).open("""w""" , encoding="""utf-8""" ) UpperCamelCase = str(__UpperCamelCase ) UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained(__UpperCamelCase ).to(__UpperCamelCase ) if fpaa: UpperCamelCase = model.half() UpperCamelCase = AutoTokenizer.from_pretrained(__UpperCamelCase ) logger.info(F"Inferred tokenizer type: {tokenizer.__class__}" ) # if this is wrong, check config.model_type. UpperCamelCase = time.time() # update config with task specific params use_task_specific_params(__UpperCamelCase , __UpperCamelCase ) if prefix is None: UpperCamelCase = prefix or getattr(model.config , """prefix""" , """""" ) or """""" for examples_chunk in tqdm(list(chunks(__UpperCamelCase , __UpperCamelCase ) ) ): UpperCamelCase = [prefix + text for text in examples_chunk] UpperCamelCase = tokenizer(__UpperCamelCase , return_tensors="""pt""" , truncation=__UpperCamelCase , padding="""longest""" ).to(__UpperCamelCase ) UpperCamelCase = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **__UpperCamelCase , ) UpperCamelCase = tokenizer.batch_decode(__UpperCamelCase , skip_special_tokens=__UpperCamelCase , clean_up_tokenization_spaces=__UpperCamelCase ) for hypothesis in dec: fout.write(hypothesis + """\n""" ) fout.flush() fout.close() UpperCamelCase = int(time.time() - start_time ) # seconds UpperCamelCase = len(__UpperCamelCase ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def lowercase__ ( )-> Dict: return datetime.datetime.now().strftime("""%Y-%m-%d %H:%M:%S""" ) def lowercase__ ( __UpperCamelCase=True )-> Optional[int]: UpperCamelCase = argparse.ArgumentParser() parser.add_argument("""model_name""" , type=__UpperCamelCase , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""input_path""" , type=__UpperCamelCase , help="""like cnn_dm/test.source""" ) parser.add_argument("""save_path""" , type=__UpperCamelCase , help="""where to save summaries""" ) parser.add_argument("""--reference_path""" , type=__UpperCamelCase , required=__UpperCamelCase , help="""like cnn_dm/test.target""" ) parser.add_argument("""--score_path""" , type=__UpperCamelCase , required=__UpperCamelCase , default="""metrics.json""" , help="""where to save metrics""" ) parser.add_argument("""--device""" , type=__UpperCamelCase , required=__UpperCamelCase , default=__UpperCamelCase , help="""cuda, cuda:1, cpu etc.""" ) parser.add_argument( """--prefix""" , type=__UpperCamelCase , required=__UpperCamelCase , default=__UpperCamelCase , help="""will be added to the begininng of src examples""" ) parser.add_argument("""--task""" , type=__UpperCamelCase , default="""summarization""" , help="""used for task_specific_params + metrics""" ) parser.add_argument("""--bs""" , type=__UpperCamelCase , default=8 , required=__UpperCamelCase , help="""batch size""" ) parser.add_argument( """--n_obs""" , type=__UpperCamelCase , default=-1 , required=__UpperCamelCase , help="""How many observations. Defaults to all.""" ) parser.add_argument("""--fp16""" , action="""store_true""" ) parser.add_argument("""--dump-args""" , action="""store_true""" , help="""print the custom hparams with the results""" ) parser.add_argument( """--info""" , nargs="""?""" , type=__UpperCamelCase , const=datetime_now() , help=( """use in conjunction w/ --dump-args to print with the results whatever other info you'd like, e.g.""" """ lang=en-ru. If no value is passed, the current datetime string will be used.""" ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate UpperCamelCase ,UpperCamelCase = parser.parse_known_args() UpperCamelCase = parse_numeric_n_bool_cl_kwargs(__UpperCamelCase ) if parsed_args and verbose: print(F"parsed the following generate kwargs: {parsed_args}" ) UpperCamelCase = [""" """ + x.rstrip() if """t5""" in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: UpperCamelCase = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=__UpperCamelCase ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(F"score_path {args.score_path} will be overwritten unless you type ctrl-c." ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError("""Can't mix --fp16 and --device cpu""" ) UpperCamelCase = generate_summaries_or_translations( __UpperCamelCase , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **__UpperCamelCase , ) if args.reference_path is None: return {} # Compute scores UpperCamelCase = calculate_bleu if """translation""" in args.task else calculate_rouge UpperCamelCase = [x.rstrip() for x in open(args.save_path ).readlines()] UpperCamelCase = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(__UpperCamelCase )] UpperCamelCase = score_fn(__UpperCamelCase , __UpperCamelCase ) scores.update(__UpperCamelCase ) if args.dump_args: scores.update(__UpperCamelCase ) if args.info: UpperCamelCase = args.info if verbose: print(__UpperCamelCase ) if args.score_path is not None: json.dump(__UpperCamelCase , open(args.score_path , """w""" ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
710
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__ = 1_6 SCREAMING_SNAKE_CASE__ = 3_2 def lowercase__ ( __UpperCamelCase , __UpperCamelCase = 16 )-> Dict: UpperCamelCase = AutoTokenizer.from_pretrained("""bert-base-cased""" ) UpperCamelCase = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__UpperCamelCase , max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCamelCase = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__UpperCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase = 16 elif accelerator.mixed_precision != "no": UpperCamelCase = 8 else: UpperCamelCase = None return tokenizer.pad( __UpperCamelCase , padding="""longest""" , max_length=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. UpperCamelCase = DataLoader( tokenized_datasets["""train"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) UpperCamelCase = DataLoader( tokenized_datasets["""validation"""] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE__ = mocked_dataloaders # noqa: F811 def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> List[Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __UpperCamelCase ) == "1": UpperCamelCase = 2 # New Code # UpperCamelCase = int(args.gradient_accumulation_steps ) UpperCamelCase = int(args.local_sgd_steps ) # Initialize accelerator UpperCamelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__UpperCamelCase ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase = config["""lr"""] UpperCamelCase = int(config["""num_epochs"""] ) UpperCamelCase = int(config["""seed"""] ) UpperCamelCase = int(config["""batch_size"""] ) UpperCamelCase = evaluate.load("""glue""" , """mrpc""" ) set_seed(__UpperCamelCase ) UpperCamelCase ,UpperCamelCase = get_dataloaders(__UpperCamelCase , __UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase = AdamW(params=model.parameters() , lr=__UpperCamelCase ) # Instantiate scheduler UpperCamelCase = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase , num_warmup_steps=100 , num_training_steps=(len(__UpperCamelCase ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = accelerator.prepare( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # Now we train the model for epoch in range(__UpperCamelCase ): model.train() with LocalSGD( accelerator=__UpperCamelCase , model=__UpperCamelCase , local_sgd_steps=__UpperCamelCase , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__UpperCamelCase ): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = output.loss accelerator.backward(__UpperCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase = model(**__UpperCamelCase ) UpperCamelCase = outputs.logits.argmax(dim=-1 ) UpperCamelCase ,UpperCamelCase = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__UpperCamelCase , references=__UpperCamelCase , ) UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __UpperCamelCase ) def lowercase__ ( )-> List[Any]: UpperCamelCase = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__UpperCamelCase , default=__UpperCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) # New Code # parser.add_argument( """--gradient_accumulation_steps""" , type=__UpperCamelCase , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , ) parser.add_argument( """--local_sgd_steps""" , type=__UpperCamelCase , default=8 , help="""Number of local SGD steps or None to disable local SGD""" ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) UpperCamelCase = parser.parse_args() UpperCamelCase = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": main()
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> 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=1_0))
711
'''simple docstring''' import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class a_ : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> Any: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = embed_dim UpperCamelCase = depths 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 = patch_norm UpperCamelCase = layer_norm_eps UpperCamelCase = initializer_range UpperCamelCase = is_training UpperCamelCase = scope UpperCamelCase = use_labels UpperCamelCase = type_sequence_label_size UpperCamelCase = encoder_stride UpperCamelCase = out_features UpperCamelCase = out_indices def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = self.get_config() return config, pixel_values, labels def A__ ( self ) -> str: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) UpperCamelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = ["""stem"""] UpperCamelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase ,UpperCamelCase ,UpperCamelCase = config_and_inputs UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class a_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowercase = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {} lowercase = False lowercase = False lowercase = False lowercase = False lowercase = False def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with""" """ `nn.DataParallel`""" ) ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self ) -> Dict: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A__ ( self ) -> int: """simple docstring""" return def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip("""Swin does not use inputs_embeds""" ) def A__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip("""Swin does not support feedforward chunking""" ) def A__ ( self ) -> Dict: """simple docstring""" pass def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_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] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" ) def A__ ( self ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" ) def A__ ( self ) -> List[str]: """simple docstring""" pass def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = outputs.hidden_states UpperCamelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = 3 UpperCamelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def A__ ( self ) -> List[Any]: """simple docstring""" pass def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): UpperCamelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( """Tuple and dict output are not equal. Difference:""" F" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:" F" {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has" F" `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}." ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True} ) @require_torch class a_ ( unittest.TestCase , lowerCamelCase ): lowercase = (MaskFormerSwinBackbone,) if is_torch_available() else () lowercase = MaskFormerSwinConfig def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = MaskFormerSwinModelTester(self ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase ,UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = inputs_dict["""pixel_values"""].shape[0] for backbone_class in self.all_model_classes: UpperCamelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: UpperCamelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
35
0
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a_ ( lowerCamelCase , unittest.TestCase ): lowercase = RobertaTokenizer lowercase = RobertaTokenizerFast lowercase = True lowercase = {"""cls_token""": """<s>"""} def A__ ( self ) -> Any: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) ) UpperCamelCase = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase = {"""unk_token""": """<unk>"""} UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def A__ ( self , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase = """lower newer""" UpperCamelCase = """lower newer""" return input_text, output_text def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase = """lower newer""" UpperCamelCase = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase = tokenizer.tokenize(_SCREAMING_SNAKE_CASE ) # , add_prefix_space=True) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = tokens + [tokenizer.unk_token] UpperCamelCase = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=_SCREAMING_SNAKE_CASE ) , [0, 31414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=_SCREAMING_SNAKE_CASE ) , [0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2] , ) @slow def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase = tokenizer.encode("""sequence builders""" , add_special_tokens=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.encode("""multi-sequence build""" , add_special_tokens=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.encode( """sequence builders""" , add_special_tokens=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.build_inputs_with_special_tokens(_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.build_inputs_with_special_tokens(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = self.get_tokenizer() UpperCamelCase = """Encode this sequence.""" UpperCamelCase = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Testing spaces after special tokens UpperCamelCase = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE )} ) # mask token has a left space UpperCamelCase = tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) UpperCamelCase = """Encode <mask> sequence""" UpperCamelCase = """Encode <mask>sequence""" UpperCamelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE ) UpperCamelCase = encoded.index(_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE ) UpperCamelCase = encoded.index(_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> int: """simple docstring""" pass def A__ ( self ) -> Union[str, Any]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase = self.rust_tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.tokenizer_class.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase = """A, <mask> AllenNLP sentence.""" UpperCamelCase = tokenizer_r.encode_plus(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_token_type_ids=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_p.encode_plus(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_token_type_ids=_SCREAMING_SNAKE_CASE ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( _SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( _SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def A__ ( self ) -> Optional[Any]: """simple docstring""" for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , _SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""add_prefix_space"""] , _SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""trim_offsets"""] , _SCREAMING_SNAKE_CASE ) def A__ ( self ) -> str: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase = self.rust_tokenizer_class.from_pretrained( _SCREAMING_SNAKE_CASE , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_r(_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_SCREAMING_SNAKE_CASE ) + 1, len(_SCREAMING_SNAKE_CASE ) + 1 + len(_SCREAMING_SNAKE_CASE )) , ) UpperCamelCase = self.rust_tokenizer_class.from_pretrained( _SCREAMING_SNAKE_CASE , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_r(_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_SCREAMING_SNAKE_CASE ) + 1, len(_SCREAMING_SNAKE_CASE ) + 1 + len(_SCREAMING_SNAKE_CASE )) , ) UpperCamelCase = self.rust_tokenizer_class.from_pretrained( _SCREAMING_SNAKE_CASE , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_r(_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_SCREAMING_SNAKE_CASE ), len(_SCREAMING_SNAKE_CASE ) + 1 + len(_SCREAMING_SNAKE_CASE )) , ) UpperCamelCase = self.rust_tokenizer_class.from_pretrained( _SCREAMING_SNAKE_CASE , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_r(_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_SCREAMING_SNAKE_CASE ), len(_SCREAMING_SNAKE_CASE ) + 1 + len(_SCREAMING_SNAKE_CASE )) , ) UpperCamelCase = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase = self.rust_tokenizer_class.from_pretrained( _SCREAMING_SNAKE_CASE , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_r(_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_SCREAMING_SNAKE_CASE ) + 1, 1 + len(_SCREAMING_SNAKE_CASE ) + 1 + len(_SCREAMING_SNAKE_CASE )) , ) UpperCamelCase = self.rust_tokenizer_class.from_pretrained( _SCREAMING_SNAKE_CASE , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_r(_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_SCREAMING_SNAKE_CASE ), 1 + len(_SCREAMING_SNAKE_CASE ) + 1 + len(_SCREAMING_SNAKE_CASE )) , ) UpperCamelCase = self.rust_tokenizer_class.from_pretrained( _SCREAMING_SNAKE_CASE , use_fast=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE ) UpperCamelCase = tokenizer_r(_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_SCREAMING_SNAKE_CASE ), 1 + len(_SCREAMING_SNAKE_CASE ) + 1 + len(_SCREAMING_SNAKE_CASE )) , )
712
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand() def lowercase__ ( __UpperCamelCase )-> str: return EnvironmentCommand(args.accelerate_config_file ) class a_ ( lowerCamelCase ): @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = parser.add_parser("""env""" ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) download_parser.add_argument( """--accelerate-config_file""" , default=_SCREAMING_SNAKE_CASE , help="""The accelerate config file to use for the default values in the launching script.""" , ) download_parser.set_defaults(func=_SCREAMING_SNAKE_CASE ) def __init__( self , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = accelerate_config_file def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = """not installed""" if is_safetensors_available(): import safetensors UpperCamelCase = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors UpperCamelCase = F"{safetensors.__version__} but is ignored because of PyTorch version too old." UpperCamelCase = """not installed""" UpperCamelCase = UpperCamelCase = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file UpperCamelCase = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_SCREAMING_SNAKE_CASE ): UpperCamelCase = load_config_from_file(self._accelerate_config_file ).to_dict() UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else F"\t{accelerate_config}" ) UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_torch_available(): import torch UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_tf_available(): import tensorflow as tf UpperCamelCase = tf.__version__ try: # deprecated in v2.1 UpperCamelCase = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool UpperCamelCase = bool(tf.config.list_physical_devices("""GPU""" ) ) UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """not installed""" UpperCamelCase = """NA""" if is_flax_available(): import flax import jax import jaxlib UpperCamelCase = flax.__version__ UpperCamelCase = jax.__version__ UpperCamelCase = jaxlib.__version__ UpperCamelCase = jax.lib.xla_bridge.get_backend().platform UpperCamelCase = { """`transformers` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Huggingface_hub version""": huggingface_hub.__version__, """Safetensors version""": F"{safetensors_version}", """Accelerate version""": F"{accelerate_version}", """Accelerate config""": F"{accelerate_config_str}", """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """Tensorflow version (GPU?)""": F"{tf_version} ({tf_cuda_available})", """Flax version (CPU?/GPU?/TPU?)""": F"{flax_version} ({jax_backend})", """Jax version""": F"{jax_version}", """JaxLib version""": F"{jaxlib_version}", """Using GPU in script?""": """<fill in>""", """Using distributed or parallel set-up in script?""": """<fill in>""", } print("""\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n""" ) print(self.format_dict(_SCREAMING_SNAKE_CASE ) ) return info @staticmethod def A__ ( _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
35
0
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin SCREAMING_SNAKE_CASE__ = random.Random() if is_torch_available(): import torch def lowercase__ ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None )-> Union[str, Any]: if rng is None: UpperCamelCase = global_rng UpperCamelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class a_ ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=2000 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=16000 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , ) -> int: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = min_seq_length UpperCamelCase = max_seq_length UpperCamelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase = feature_size UpperCamelCase = padding_value UpperCamelCase = sampling_rate UpperCamelCase = return_attention_mask UpperCamelCase = do_normalize def A__ ( self ) -> List[str]: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def A__ ( self , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" def _flatten(_SCREAMING_SNAKE_CASE ): return list(itertools.chain(*_SCREAMING_SNAKE_CASE ) ) if equal_length: UpperCamelCase = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size UpperCamelCase = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: UpperCamelCase = [np.asarray(_SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class a_ ( lowerCamelCase , unittest.TestCase ): lowercase = ASTFeatureExtractor def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = ASTFeatureExtractionTester(self ) def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCamelCase = [np.asarray(_SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test not batched input UpperCamelCase = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values UpperCamelCase = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test batched UpperCamelCase = feat_extract(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_values UpperCamelCase = feat_extract(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase = np.asarray(_SCREAMING_SNAKE_CASE ) UpperCamelCase = feat_extract(_SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_values UpperCamelCase = feat_extract(_SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) @require_torch def A__ ( self ) -> str: """simple docstring""" import torch UpperCamelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase = np.random.rand(100 ).astype(np.floataa ) UpperCamelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) UpperCamelCase = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" from datasets import load_dataset UpperCamelCase = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech UpperCamelCase = ds.sort("""id""" ).select(range(_SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] @require_torch def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = torch.tensor( [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6, -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3, -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6, -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9] ) # fmt: on UpperCamelCase = self._load_datasamples(1 ) UpperCamelCase = ASTFeatureExtractor() UpperCamelCase = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
713
'''simple docstring''' from math import factorial def lowercase__ ( __UpperCamelCase = 20 )-> int: UpperCamelCase = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCamelCase = n // 2 return int(factorial(__UpperCamelCase ) / (factorial(__UpperCamelCase ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: SCREAMING_SNAKE_CASE__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
35
0
'''simple docstring''' from timeit import timeit def lowercase__ ( __UpperCamelCase )-> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase = 0 while number: number &= number - 1 result += 1 return result def lowercase__ ( __UpperCamelCase )-> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowercase__ ( )-> None: def do_benchmark(__UpperCamelCase ) -> None: UpperCamelCase = """import __main__ as z""" print(F"Benchmark when {number = }:" ) print(F"{get_set_bits_count_using_modulo_operator(__UpperCamelCase ) = }" ) UpperCamelCase = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__UpperCamelCase ) print(F"timeit() runs in {timing} seconds" ) print(F"{get_set_bits_count_using_brian_kernighans_algorithm(__UpperCamelCase ) = }" ) UpperCamelCase = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__UpperCamelCase , ) print(F"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__UpperCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
714
'''simple docstring''' from math import sqrt def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = 0 for i in range(1 , int(sqrt(__UpperCamelCase ) + 1 ) ): if n % i == 0 and i != sqrt(__UpperCamelCase ): total += i + n // i elif i == sqrt(__UpperCamelCase ): total += i return total - n def lowercase__ ( __UpperCamelCase = 10000 )-> int: UpperCamelCase = sum( i for i in range(1 , __UpperCamelCase ) if sum_of_divisors(sum_of_divisors(__UpperCamelCase ) ) == i and sum_of_divisors(__UpperCamelCase ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
35
0
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> None: UpperCamelCase = len(__UpperCamelCase ) print("""The following activities are selected:""" ) # The first activity is always selected UpperCamelCase = 0 print(__UpperCamelCase , end=""",""" ) # Consider rest of the activities for j in range(__UpperCamelCase ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(__UpperCamelCase , end=""",""" ) UpperCamelCase = j if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE__ = [1, 3, 0, 5, 8, 5] SCREAMING_SNAKE_CASE__ = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
715
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
35
0
'''simple docstring''' import sys def lowercase__ ( __UpperCamelCase )-> int: UpperCamelCase = len(__UpperCamelCase ) UpperCamelCase = [[0 for x in range(__UpperCamelCase )] for x in range(__UpperCamelCase )] UpperCamelCase = [[0 for x in range(__UpperCamelCase )] for x in range(__UpperCamelCase )] for chain_length in range(2 , __UpperCamelCase ): for a in range(1 , n - chain_length + 1 ): UpperCamelCase = a + chain_length - 1 UpperCamelCase = sys.maxsize for c in range(__UpperCamelCase , __UpperCamelCase ): UpperCamelCase = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: UpperCamelCase = cost UpperCamelCase = c return matrix, sol def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Optional[int]: if i == j: print("""A""" + str(__UpperCamelCase ) , end=""" """ ) else: print("""(""" , end=""" """ ) print_optiomal_solution(__UpperCamelCase , __UpperCamelCase , optimal_solution[i][j] ) print_optiomal_solution(__UpperCamelCase , optimal_solution[i][j] + 1 , __UpperCamelCase ) print(""")""" , end=""" """ ) def lowercase__ ( )-> Optional[Any]: UpperCamelCase = [30, 35, 15, 5, 10, 20, 25] UpperCamelCase = len(__UpperCamelCase ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 UpperCamelCase ,UpperCamelCase = matrix_chain_order(__UpperCamelCase ) print("""No. of Operation required: """ + str(matrix[1][n - 1] ) ) print_optiomal_solution(__UpperCamelCase , 1 , n - 1 ) if __name__ == "__main__": main()
716
'''simple docstring''' def lowercase__ ( __UpperCamelCase )-> str: if not all(char in """01""" for char in bin_string ): raise ValueError("""Non-binary value was passed to the function""" ) if not bin_string: raise ValueError("""Empty string was passed to the function""" ) UpperCamelCase = """""" while len(__UpperCamelCase ) % 3 != 0: UpperCamelCase = """0""" + bin_string UpperCamelCase = [ bin_string[index : index + 3] for index in range(len(__UpperCamelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: UpperCamelCase = 0 for index, val in enumerate(__UpperCamelCase ): oct_val += int(2 ** (2 - index) * int(__UpperCamelCase ) ) oct_string += str(__UpperCamelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
35
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class a_ ( unittest.TestCase ): '''simple docstring''' lowercase = MODEL_FOR_CAUSAL_LM_MAPPING lowercase = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = pipeline(task="""text-generation""" , model="""sshleifer/tiny-ctrl""" , framework="""pt""" ) # Using `do_sample=False` to force deterministic output UpperCamelCase = text_generator("""This is a test""" , do_sample=_SCREAMING_SNAKE_CASE ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ { """generated_text""": ( """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.""" """ oscope. FiliFili@@""" ) } ] , ) UpperCamelCase = text_generator(["""This is a test""", """This is a second test"""] ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ [ { """generated_text""": ( """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.""" """ oscope. FiliFili@@""" ) } ], [ { """generated_text""": ( """This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy""" """ oscope. oscope. FiliFili@@""" ) } ], ] , ) UpperCamelCase = text_generator("""This is a test""" , do_sample=_SCREAMING_SNAKE_CASE , num_return_sequences=2 , return_tensors=_SCREAMING_SNAKE_CASE ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ {"""generated_token_ids""": ANY(_SCREAMING_SNAKE_CASE )}, {"""generated_token_ids""": ANY(_SCREAMING_SNAKE_CASE )}, ] , ) UpperCamelCase = text_generator.model.config.eos_token_id UpperCamelCase = """<pad>""" UpperCamelCase = text_generator( ["""This is a test""", """This is a second test"""] , do_sample=_SCREAMING_SNAKE_CASE , num_return_sequences=2 , batch_size=2 , return_tensors=_SCREAMING_SNAKE_CASE , ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ [ {"""generated_token_ids""": ANY(_SCREAMING_SNAKE_CASE )}, {"""generated_token_ids""": ANY(_SCREAMING_SNAKE_CASE )}, ], [ {"""generated_token_ids""": ANY(_SCREAMING_SNAKE_CASE )}, {"""generated_token_ids""": ANY(_SCREAMING_SNAKE_CASE )}, ], ] , ) @require_tf def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = pipeline(task="""text-generation""" , model="""sshleifer/tiny-ctrl""" , framework="""tf""" ) # Using `do_sample=False` to force deterministic output UpperCamelCase = text_generator("""This is a test""" , do_sample=_SCREAMING_SNAKE_CASE ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ { """generated_text""": ( """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵""" """ please,""" ) } ] , ) UpperCamelCase = text_generator(["""This is a test""", """This is a second test"""] , do_sample=_SCREAMING_SNAKE_CASE ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ [ { """generated_text""": ( """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵""" """ please,""" ) } ], [ { """generated_text""": ( """This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes""" """ Cannes 閲閲Cannes Cannes Cannes 攵 please,""" ) } ], ] , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = TextGenerationPipeline(model=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) return text_generator, ["This is a test", "Another test"] def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = """Hello I believe in""" UpperCamelCase = pipeline("""text-generation""" , model="""hf-internal-testing/tiny-random-gpt2""" ) UpperCamelCase = text_generator(_SCREAMING_SNAKE_CASE ) self.assertEqual( _SCREAMING_SNAKE_CASE , [{"""generated_text""": """Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"""}] , ) UpperCamelCase = text_generator(_SCREAMING_SNAKE_CASE , stop_sequence=""" fe""" ) self.assertEqual(_SCREAMING_SNAKE_CASE , [{"""generated_text""": """Hello I believe in fe"""}] ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" UpperCamelCase = text_generator.model UpperCamelCase = text_generator.tokenizer UpperCamelCase = text_generator("""This is a test""" ) self.assertEqual(_SCREAMING_SNAKE_CASE , [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}] ) self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test""" ) ) UpperCamelCase = text_generator("""This is a test""" , return_full_text=_SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}] ) self.assertNotIn("""This is a test""" , outputs[0]["""generated_text"""] ) UpperCamelCase = pipeline(task="""text-generation""" , model=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , return_full_text=_SCREAMING_SNAKE_CASE ) UpperCamelCase = text_generator("""This is a test""" ) self.assertEqual(_SCREAMING_SNAKE_CASE , [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}] ) self.assertNotIn("""This is a test""" , outputs[0]["""generated_text"""] ) UpperCamelCase = text_generator("""This is a test""" , return_full_text=_SCREAMING_SNAKE_CASE ) self.assertEqual(_SCREAMING_SNAKE_CASE , [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}] ) self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test""" ) ) UpperCamelCase = text_generator(["""This is great !""", """Something else"""] , num_return_sequences=2 , do_sample=_SCREAMING_SNAKE_CASE ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}, {"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}], [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}, {"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}], ] , ) if text_generator.tokenizer.pad_token is not None: UpperCamelCase = text_generator( ["""This is great !""", """Something else"""] , num_return_sequences=2 , batch_size=2 , do_sample=_SCREAMING_SNAKE_CASE ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}, {"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}], [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}, {"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}], ] , ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = text_generator("""test""" , return_full_text=_SCREAMING_SNAKE_CASE , return_text=_SCREAMING_SNAKE_CASE ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = text_generator("""test""" , return_full_text=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): UpperCamelCase = text_generator("""test""" , return_text=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): UpperCamelCase = text_generator("""""" ) self.assertEqual(_SCREAMING_SNAKE_CASE , [{"""generated_text""": ANY(_SCREAMING_SNAKE_CASE )}] ) else: with self.assertRaises((ValueError, AssertionError) ): UpperCamelCase = text_generator("""""" ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. UpperCamelCase = ["""RwkvForCausalLM""", """XGLMForCausalLM""", """GPTNeoXForCausalLM"""] if ( tokenizer.model_max_length < 10000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator("""This is a test""" * 500 , max_new_tokens=20 ) UpperCamelCase = text_generator("""This is a test""" * 500 , handle_long_generation="""hole""" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(_SCREAMING_SNAKE_CASE ): text_generator( """This is a test""" * 500 , handle_long_generation="""hole""" , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def A__ ( self ) -> Union[str, Any]: """simple docstring""" import torch # Classic `model_kwargs` UpperCamelCase = pipeline( model="""hf-internal-testing/tiny-random-bloom""" , model_kwargs={"""device_map""": """auto""", """torch_dtype""": torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) UpperCamelCase = pipe("""This is a test""" ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) UpperCamelCase = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device_map="""auto""" , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) UpperCamelCase = pipe("""This is a test""" ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 UpperCamelCase = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device_map="""auto""" ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) UpperCamelCase = pipe("""This is a test""" ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ { """generated_text""": ( """This is a test test test test test test test test test test test test test test test test""" """ test""" ) } ] , ) @require_torch @require_torch_gpu def A__ ( self ) -> List[Any]: """simple docstring""" import torch UpperCamelCase = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device=0 , torch_dtype=torch.floataa ) pipe("""This is a test""" ) @require_torch @require_accelerate @require_torch_gpu def A__ ( self ) -> List[str]: """simple docstring""" import torch UpperCamelCase = pipeline(model="""hf-internal-testing/tiny-random-bloom""" , device_map="""auto""" , torch_dtype=torch.floataa ) pipe("""This is a test""" , do_sample=_SCREAMING_SNAKE_CASE , top_p=0.5 ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = """Hello world""" UpperCamelCase = pipeline("""text-generation""" , model="""hf-internal-testing/tiny-random-gpt2""" ) if text_generator.model.framework == "tf": UpperCamelCase = logging.get_logger("""transformers.generation.tf_utils""" ) else: UpperCamelCase = logging.get_logger("""transformers.generation.utils""" ) UpperCamelCase = """Both `max_new_tokens`""" # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(_SCREAMING_SNAKE_CASE ) as cl: UpperCamelCase = text_generator(_SCREAMING_SNAKE_CASE , max_length=10 , max_new_tokens=1 ) self.assertIn(_SCREAMING_SNAKE_CASE , cl.out ) # The user only sets one -> no warning with CaptureLogger(_SCREAMING_SNAKE_CASE ) as cl: UpperCamelCase = text_generator(_SCREAMING_SNAKE_CASE , max_new_tokens=1 ) self.assertNotIn(_SCREAMING_SNAKE_CASE , cl.out ) with CaptureLogger(_SCREAMING_SNAKE_CASE ) as cl: UpperCamelCase = text_generator(_SCREAMING_SNAKE_CASE , max_length=10 ) self.assertNotIn(_SCREAMING_SNAKE_CASE , cl.out )
717
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def lowercase__ ( __UpperCamelCase=None )-> Union[str, Any]: if subparsers is not None: UpperCamelCase = subparsers.add_parser("""env""" ) else: UpperCamelCase = argparse.ArgumentParser("""Accelerate env command""" ) parser.add_argument( """--config_file""" , default=__UpperCamelCase , help="""The config file to use for the default values in the launching script.""" ) if subparsers is not None: parser.set_defaults(func=__UpperCamelCase ) return parser def lowercase__ ( __UpperCamelCase )-> List[str]: UpperCamelCase = torch.__version__ UpperCamelCase = torch.cuda.is_available() UpperCamelCase = is_xpu_available() UpperCamelCase = is_npu_available() UpperCamelCase = """Not found""" # Get the default from the config file. if args.config_file is not None or os.path.isfile(__UpperCamelCase ): UpperCamelCase = load_config_from_file(args.config_file ).to_dict() UpperCamelCase = { """`Accelerate` version""": version, """Platform""": platform.platform(), """Python version""": platform.python_version(), """Numpy version""": np.__version__, """PyTorch version (GPU?)""": F"{pt_version} ({pt_cuda_available})", """PyTorch XPU available""": str(__UpperCamelCase ), """PyTorch NPU available""": str(__UpperCamelCase ), """System RAM""": F"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", } if pt_cuda_available: UpperCamelCase = torch.cuda.get_device_name() print("""\nCopy-and-paste the text below in your GitHub issue\n""" ) print("""\n""".join([F"- {prop}: {val}" for prop, val in info.items()] ) ) print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" ) UpperCamelCase = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else F"\t{accelerate_config}" ) print(__UpperCamelCase ) UpperCamelCase = accelerate_config return info def lowercase__ ( )-> int: UpperCamelCase = env_command_parser() UpperCamelCase = parser.parse_args() env_command(__UpperCamelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
35
0
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) def lowercase__ ( __UpperCamelCase )-> Dict: UpperCamelCase = torch.load(__UpperCamelCase , map_location="""cpu""" ) if "model" in sd.keys(): UpperCamelCase = torch.load(__UpperCamelCase , map_location="""cpu""" )["""model"""] # pop unnecessary weights UpperCamelCase = [ """decoder.version""", """decoder.output_projection.weight""", ] for key in keys_to_delete: if key in sd: sd.pop(__UpperCamelCase ) UpperCamelCase = { """decoder.project_in_dim.weight""": """decoder.project_in.weight""", """decoder.project_out_dim.weight""": """decoder.project_out.weight""", """decoder.layer_norm.weight""": """decoder.final_layer_norm.weight""", """decoder.layer_norm.bias""": """decoder.final_layer_norm.bias""", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: UpperCamelCase = sd.pop(__UpperCamelCase ) UpperCamelCase = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: UpperCamelCase = sd[key] # We split QKV in separate Q,K,V UpperCamelCase = key.replace(""".qkv_proj.""" , """.q_proj.""" ) UpperCamelCase = key.replace(""".qkv_proj.""" , """.k_proj.""" ) UpperCamelCase = key.replace(""".qkv_proj.""" , """.v_proj.""" ) UpperCamelCase = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 UpperCamelCase ,UpperCamelCase ,UpperCamelCase = torch.split(__UpperCamelCase , depth // 3 , dim=0 ) UpperCamelCase = q UpperCamelCase = k UpperCamelCase = v del sd[key] return sd @torch.no_grad() def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None )-> Any: UpperCamelCase = load_checkpoint(__UpperCamelCase ) if config is not None: UpperCamelCase = OPTConfig.from_pretrained(__UpperCamelCase ) else: UpperCamelCase = OPTConfig() UpperCamelCase = OPTModel(__UpperCamelCase ).half().eval() model.load_state_dict(__UpperCamelCase ) # Check results Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) model.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--fairseq_path', type=str, help=( 'path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:' ' https://huggingface.co/models?other=opt_metasq' ), ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--hf_config', default=None, type=str, help='Define HF config.') SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
718
'''simple docstring''' def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str: if not isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError("""iterations must be defined as integers""" ) if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" ) UpperCamelCase = """""" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(__UpperCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
35
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Swinv2ForImageClassification', 'Swinv2ForMaskedImageModeling', 'Swinv2Model', 'Swinv2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
719
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def lowercase__ ( __UpperCamelCase , __UpperCamelCase=1 )-> Tuple: if n_shave_prefix_segments >= 0: return ".".join(path.split(""".""" )[n_shave_prefix_segments:] ) else: return ".".join(path.split(""".""" )[:n_shave_prefix_segments] ) def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> Dict: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item.replace("""in_layers.0""" , """norm1""" ) UpperCamelCase = new_item.replace("""in_layers.2""" , """conv1""" ) UpperCamelCase = new_item.replace("""out_layers.0""" , """norm2""" ) UpperCamelCase = new_item.replace("""out_layers.3""" , """conv2""" ) UpperCamelCase = new_item.replace("""emb_layers.1""" , """time_emb_proj""" ) UpperCamelCase = new_item.replace("""skip_connection""" , """conv_shortcut""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase=0 )-> List[str]: UpperCamelCase = [] for old_item in old_list: UpperCamelCase = old_item UpperCamelCase = new_item.replace("""norm.weight""" , """group_norm.weight""" ) UpperCamelCase = new_item.replace("""norm.bias""" , """group_norm.bias""" ) UpperCamelCase = new_item.replace("""proj_out.weight""" , """proj_attn.weight""" ) UpperCamelCase = new_item.replace("""proj_out.bias""" , """proj_attn.bias""" ) UpperCamelCase = shave_segments(__UpperCamelCase , n_shave_prefix_segments=__UpperCamelCase ) mapping.append({"""old""": old_item, """new""": new_item} ) return mapping def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=None )-> str: assert isinstance(__UpperCamelCase , __UpperCamelCase ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): UpperCamelCase = old_checkpoint[path] UpperCamelCase = old_tensor.shape[0] // 3 UpperCamelCase = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) UpperCamelCase = old_tensor.shape[0] // config["""num_head_channels"""] // 3 UpperCamelCase = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) UpperCamelCase ,UpperCamelCase ,UpperCamelCase = old_tensor.split(channels // num_heads , dim=1 ) UpperCamelCase = query.reshape(__UpperCamelCase ) UpperCamelCase = key.reshape(__UpperCamelCase ) UpperCamelCase = value.reshape(__UpperCamelCase ) for path in paths: UpperCamelCase = path["""new"""] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here UpperCamelCase = new_path.replace("""middle_block.0""" , """mid_block.resnets.0""" ) UpperCamelCase = new_path.replace("""middle_block.1""" , """mid_block.attentions.0""" ) UpperCamelCase = new_path.replace("""middle_block.2""" , """mid_block.resnets.1""" ) if additional_replacements is not None: for replacement in additional_replacements: UpperCamelCase = new_path.replace(replacement["""old"""] , replacement["""new"""] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: UpperCamelCase = old_checkpoint[path["""old"""]][:, :, 0] else: UpperCamelCase = old_checkpoint[path["""old"""]] def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> Optional[int]: UpperCamelCase = {} UpperCamelCase = checkpoint["""time_embed.0.weight"""] UpperCamelCase = checkpoint["""time_embed.0.bias"""] UpperCamelCase = checkpoint["""time_embed.2.weight"""] UpperCamelCase = checkpoint["""time_embed.2.bias"""] UpperCamelCase = checkpoint["""input_blocks.0.0.weight"""] UpperCamelCase = checkpoint["""input_blocks.0.0.bias"""] UpperCamelCase = checkpoint["""out.0.weight"""] UpperCamelCase = checkpoint["""out.0.bias"""] UpperCamelCase = checkpoint["""out.2.weight"""] UpperCamelCase = checkpoint["""out.2.bias"""] # Retrieves the keys for the input blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """input_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"input_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the middle blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """middle_block""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"middle_block.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } # Retrieves the keys for the output blocks only UpperCamelCase = len({""".""".join(layer.split(""".""" )[:2] ) for layer in checkpoint if """output_blocks""" in layer} ) UpperCamelCase = { layer_id: [key for key in checkpoint if F"output_blocks.{layer_id}" in key] for layer_id in range(__UpperCamelCase ) } for i in range(1 , __UpperCamelCase ): UpperCamelCase = (i - 1) // (config["""num_res_blocks"""] + 1) UpperCamelCase = (i - 1) % (config["""num_res_blocks"""] + 1) UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.0" in key] UpperCamelCase = [key for key in input_blocks[i] if F"input_blocks.{i}.1" in key] if F"input_blocks.{i}.0.op.weight" in checkpoint: UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.weight" ] UpperCamelCase = checkpoint[ F"input_blocks.{i}.0.op.bias" ] continue UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"input_blocks.{i}.0", """new""": F"down_blocks.{block_id}.resnets.{layer_in_block_id}"} UpperCamelCase = {"""old""": """resnets.2.op""", """new""": """downsamplers.0.op"""} assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path, resnet_op] , config=__UpperCamelCase ) if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"input_blocks.{i}.1", """new""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"input_blocks.{i}.1.qkv.bias": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"input_blocks.{i}.1.qkv.weight": { """key""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase , ) UpperCamelCase = middle_blocks[0] UpperCamelCase = middle_blocks[1] UpperCamelCase = middle_blocks[2] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , config=__UpperCamelCase ) UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """middle_block.1.qkv.bias""": { """key""": """mid_block.attentions.0.key.bias""", """query""": """mid_block.attentions.0.query.bias""", """value""": """mid_block.attentions.0.value.bias""", }, """middle_block.1.qkv.weight""": { """key""": """mid_block.attentions.0.key.weight""", """query""": """mid_block.attentions.0.query.weight""", """value""": """mid_block.attentions.0.value.weight""", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , attention_paths_to_split=__UpperCamelCase , config=__UpperCamelCase ) for i in range(__UpperCamelCase ): UpperCamelCase = i // (config["""num_res_blocks"""] + 1) UpperCamelCase = i % (config["""num_res_blocks"""] + 1) UpperCamelCase = [shave_segments(__UpperCamelCase , 2 ) for name in output_blocks[i]] UpperCamelCase = {} for layer in output_block_layers: UpperCamelCase ,UpperCamelCase = layer.split(""".""" )[0], shave_segments(__UpperCamelCase , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__UpperCamelCase ) else: UpperCamelCase = [layer_name] if len(__UpperCamelCase ) > 1: UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.0" in key] UpperCamelCase = [key for key in output_blocks[i] if F"output_blocks.{i}.1" in key] UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = renew_resnet_paths(__UpperCamelCase ) UpperCamelCase = {"""old""": F"output_blocks.{i}.0", """new""": F"up_blocks.{block_id}.resnets.{layer_in_block_id}"} assign_to_checkpoint(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , config=__UpperCamelCase ) if ["conv.weight", "conv.bias"] in output_block_list.values(): UpperCamelCase = list(output_block_list.values() ).index(["""conv.weight""", """conv.bias"""] ) UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.weight" ] UpperCamelCase = checkpoint[ F"output_blocks.{i}.{index}.conv.bias" ] # Clear attentions as they have been attributed above. if len(__UpperCamelCase ) == 2: UpperCamelCase = [] if len(__UpperCamelCase ): UpperCamelCase = renew_attention_paths(__UpperCamelCase ) UpperCamelCase = { """old""": F"output_blocks.{i}.1", """new""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}", } UpperCamelCase = { F"output_blocks.{i}.1.qkv.bias": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias", }, F"output_blocks.{i}.1.qkv.weight": { """key""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight", """query""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight", """value""": F"up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight", }, } assign_to_checkpoint( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any("""qkv""" in key for key in attentions ) else None , config=__UpperCamelCase , ) else: UpperCamelCase = renew_resnet_paths(__UpperCamelCase , n_shave_prefix_segments=1 ) for path in resnet_0_paths: UpperCamelCase = """.""".join(["""output_blocks""", str(__UpperCamelCase ), path["""old"""]] ) UpperCamelCase = """.""".join(["""up_blocks""", str(__UpperCamelCase ), """resnets""", str(__UpperCamelCase ), path["""new"""]] ) UpperCamelCase = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = torch.load(args.checkpoint_path) with open(args.config_file) as f: SCREAMING_SNAKE_CASE__ = json.loads(f.read()) SCREAMING_SNAKE_CASE__ = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] SCREAMING_SNAKE_CASE__ = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: SCREAMING_SNAKE_CASE__ = DDPMScheduler.from_config('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = VQModel.from_pretrained('/'.join(args.checkpoint_path.split('/')[:-1])) SCREAMING_SNAKE_CASE__ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
35
0
from math import factorial def lowercase__ ( __UpperCamelCase = 20 )-> int: UpperCamelCase = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... UpperCamelCase = n // 2 return int(factorial(__UpperCamelCase ) / (factorial(__UpperCamelCase ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: SCREAMING_SNAKE_CASE__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
720
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> dict[str, float]: if (voltage, current, resistance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance < 0: raise ValueError("""Resistance cannot be negative""" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' SCREAMING_SNAKE_CASE__ = 8.31_44_62 # Unit - J mol-1 K-1 def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
721
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration SCREAMING_SNAKE_CASE__ = 'facebook/wmt19-en-de' SCREAMING_SNAKE_CASE__ = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model SCREAMING_SNAKE_CASE__ = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) SCREAMING_SNAKE_CASE__ = FSMTForConditionalGeneration(config) print(f'num of params {tiny_model.num_parameters()}') # Test SCREAMING_SNAKE_CASE__ = tokenizer(['Making tiny model'], return_tensors='pt') SCREAMING_SNAKE_CASE__ = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save SCREAMING_SNAKE_CASE__ = 'tiny-wmt19-en-de' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(f'Generated {mname_tiny}') # Upload # transformers-cli upload tiny-wmt19-en-de
35
0
'''simple docstring''' import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __a = logging.get_logger(__name__) __a = 'https://openaipublic.azureedge.net/jukebox/models/' __a = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def lowercase__ ( __UpperCamelCase )-> Dict: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: UpperCamelCase = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: UpperCamelCase = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: UpperCamelCase = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: UpperCamelCase = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: UpperCamelCase = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: UpperCamelCase = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: UpperCamelCase = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: UpperCamelCase = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Tuple: UpperCamelCase = {} import re UpperCamelCase = re.compile(R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) UpperCamelCase = re.compile( R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) UpperCamelCase = re.compile(R"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) UpperCamelCase = re.compile(R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) UpperCamelCase = re.compile( R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) UpperCamelCase = re.compile(R"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) UpperCamelCase = re.compile(R"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) UpperCamelCase = re.compile( R"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) UpperCamelCase = re.compile(R"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(__UpperCamelCase ): UpperCamelCase = re_encoder_block_conv_in.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}" UpperCamelCase = re_encoder_block_conv_in.sub(__UpperCamelCase , __UpperCamelCase ) elif re_encoder_block_resnet.fullmatch(__UpperCamelCase ): UpperCamelCase = re_encoder_block_resnet.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase = {"""1""": 1, """3""": 2}[groups[-2]] UpperCamelCase = F"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}." UpperCamelCase = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" UpperCamelCase = prefix + resnet_block UpperCamelCase = re_encoder_block_resnet.sub(__UpperCamelCase , __UpperCamelCase ) elif re_encoder_block_proj_out.fullmatch(__UpperCamelCase ): UpperCamelCase = re_encoder_block_proj_out.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = F"encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}" UpperCamelCase = re_encoder_block_proj_out.sub(__UpperCamelCase , __UpperCamelCase ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(__UpperCamelCase ): UpperCamelCase = re_decoder_block_conv_out.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}" UpperCamelCase = re_decoder_block_conv_out.sub(__UpperCamelCase , __UpperCamelCase ) elif re_decoder_block_resnet.fullmatch(__UpperCamelCase ): UpperCamelCase = re_decoder_block_resnet.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase = {"""1""": 1, """3""": 2}[groups[-2]] UpperCamelCase = F"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}." UpperCamelCase = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" UpperCamelCase = prefix + resnet_block UpperCamelCase = re_decoder_block_resnet.sub(__UpperCamelCase , __UpperCamelCase ) elif re_decoder_block_proj_in.fullmatch(__UpperCamelCase ): UpperCamelCase = re_decoder_block_proj_in.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = F"decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}" UpperCamelCase = re_decoder_block_proj_in.sub(__UpperCamelCase , __UpperCamelCase ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(__UpperCamelCase ): UpperCamelCase = re_prior_cond_conv_out.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase = F"conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}" UpperCamelCase = re_prior_cond_conv_out.sub(__UpperCamelCase , __UpperCamelCase ) elif re_prior_cond_resnet.fullmatch(__UpperCamelCase ): UpperCamelCase = re_prior_cond_resnet.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase = {"""1""": 1, """3""": 2}[groups[-2]] UpperCamelCase = F"conditioner_blocks.upsampler.upsample_block.{block_index}." UpperCamelCase = F"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" UpperCamelCase = prefix + resnet_block UpperCamelCase = re_prior_cond_resnet.sub(__UpperCamelCase , __UpperCamelCase ) elif re_prior_cond_proj_in.fullmatch(__UpperCamelCase ): UpperCamelCase = re_prior_cond_proj_in.match(__UpperCamelCase ) UpperCamelCase = regex_match.groups() UpperCamelCase = F"conditioner_blocks.upsampler.proj_in.{groups[-1]}" UpperCamelCase = re_prior_cond_proj_in.sub(__UpperCamelCase , __UpperCamelCase ) # keep original key else: UpperCamelCase = original_key UpperCamelCase = replace_key(__UpperCamelCase ) if F"{key_prefix}.{key}" not in model_state_dict or key is None: print(F"failed converting {original_key} to {key}, does not match" ) # handle missmatched shape elif value.shape != model_state_dict[F"{key_prefix}.{key}"].shape: UpperCamelCase = model_state_dict[F"{key_prefix}.{key}"] print(F"{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match" ) UpperCamelCase = original_key UpperCamelCase = original_key UpperCamelCase = value return new_dict @torch.no_grad() def lowercase__ ( __UpperCamelCase=None , __UpperCamelCase=None )-> Optional[Any]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" ): UpperCamelCase = requests.get(F"{PREFIX}{file}" , allow_redirects=__UpperCamelCase ) os.makedirs(F"{pytorch_dump_folder_path}/" , exist_ok=__UpperCamelCase ) open(F"{pytorch_dump_folder_path}/{file.split('/' )[-1]}" , """wb""" ).write(r.content ) UpperCamelCase = MODEL_MAPPING[model_name.split("""/""" )[-1]] UpperCamelCase = JukeboxConfig.from_pretrained(__UpperCamelCase ) UpperCamelCase = JukeboxModel(__UpperCamelCase ) UpperCamelCase = [] UpperCamelCase = {} for i, dict_name in enumerate(__UpperCamelCase ): UpperCamelCase = torch.load(F"{pytorch_dump_folder_path}/{dict_name.split('/' )[-1]}" )["""model"""] UpperCamelCase = {} for k in old_dic.keys(): if k.endswith(""".b""" ): UpperCamelCase = old_dic[k] elif k.endswith(""".w""" ): UpperCamelCase = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: UpperCamelCase = old_dic[k] else: UpperCamelCase = old_dic[k] UpperCamelCase = """vqvae""" if i == 0 else F"priors.{3 - i}" UpperCamelCase = fix_jukebox_keys(__UpperCamelCase , model.state_dict() , __UpperCamelCase , __UpperCamelCase ) weight_dict.append(__UpperCamelCase ) UpperCamelCase = weight_dict.pop(0 ) model.vqvae.load_state_dict(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) with open(F"{pytorch_dump_folder_path}/mapping.json" , """w""" ) as txtfile: json.dump(__UpperCamelCase , __UpperCamelCase ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__UpperCamelCase ) return weight_dict if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __a = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
700
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) SCREAMING_SNAKE_CASE__ = CLIPImageProcessor() SCREAMING_SNAKE_CASE__ = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') SCREAMING_SNAKE_CASE__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
35
0
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class a_ ( unittest.TestCase ): lowercase = inspect.getfile(accelerate.test_utils ) lowercase = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_cli.py"""] ) lowercase = ["""accelerate""", """launch"""] lowercase = Path.home() / """.cache/huggingface/accelerate""" lowercase = """default_config.yaml""" lowercase = config_folder / config_file lowercase = config_folder / """_default_config.yaml""" lowercase = Path("""tests/test_configs""" ) @classmethod def A__ ( cls ) -> int: """simple docstring""" if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def A__ ( cls ) -> List[Any]: """simple docstring""" if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def A__ ( self ) -> Any: """simple docstring""" for config in sorted(self.test_config_path.glob("""**/*.yaml""" ) ): with self.subTest(config_file=_SCREAMING_SNAKE_CASE ): execute_subprocess_async( self.base_cmd + ["""--config_file""", str(_SCREAMING_SNAKE_CASE ), self.test_file_path] , env=os.environ.copy() ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" execute_subprocess_async(["""accelerate""", """test"""] , env=os.environ.copy() ) class a_ ( unittest.TestCase ): lowercase = """test-tpu""" lowercase = """us-central1-a""" lowercase = """ls""" lowercase = ["""accelerate""", """tpu-config"""] lowercase = """cd /usr/share""" lowercase = """tests/test_samples/test_command_file.sh""" lowercase = """Running gcloud compute tpus tpu-vm ssh""" def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = run_command( self.cmd + ["""--command""", self.command, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug"""] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = run_command( self.cmd + [ """--config_file""", """tests/test_configs/0_12_0.yaml""", """--command""", self.command, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug""", ] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--debug"""] , return_stdout=_SCREAMING_SNAKE_CASE ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> int: """simple docstring""" UpperCamelCase = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--command""", self.command, """--debug"""] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = run_command( self.cmd + [ """--config_file""", """tests/test_configs/latest.yaml""", """--command""", self.command, """--command""", """echo \"Hello World\"""", """--debug""", ] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--command_file""", self.command_file, """--debug"""] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = run_command( self.cmd + [ """--config_file""", """tests/test_configs/0_12_0.yaml""", """--command_file""", self.command_file, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug""", ] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--install_accelerate""", """--debug"""] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all" , _SCREAMING_SNAKE_CASE , ) def A__ ( self ) -> str: """simple docstring""" UpperCamelCase = run_command( self.cmd + [ """--config_file""", """tests/test_configs/latest.yaml""", """--install_accelerate""", """--accelerate_version""", """12.0.0""", """--debug""", ] , return_stdout=_SCREAMING_SNAKE_CASE , ) self.assertIn( F"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all" , _SCREAMING_SNAKE_CASE , )
701
'''simple docstring''' from __future__ import annotations from typing import Any class a_ : def __init__( self , _SCREAMING_SNAKE_CASE = 6 ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None self.create_linked_list(_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = current_node UpperCamelCase = current_node for _ in range(1 , _SCREAMING_SNAKE_CASE ): UpperCamelCase = Node() UpperCamelCase = current_node UpperCamelCase = previous_node UpperCamelCase = current_node UpperCamelCase = self.front UpperCamelCase = previous_node def A__ ( self ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCamelCase = self.rear.next if self.rear: UpperCamelCase = data def A__ ( self ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCamelCase = self.front.data UpperCamelCase = None return data UpperCamelCase = self.front UpperCamelCase = old_front.next UpperCamelCase = old_front.data UpperCamelCase = None return data def A__ ( self ) -> None: """simple docstring""" if self.is_empty(): raise Exception("""Empty Queue""" ) def A__ ( self ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class a_ : def __init__( self ) -> None: """simple docstring""" UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class a_ ( lowerCamelCase , lowerCamelCase ): @register_to_config def __init__( self , _SCREAMING_SNAKE_CASE = 768 , ) -> List[Any]: """simple docstring""" super().__init__() UpperCamelCase = nn.Parameter(torch.zeros(1 , _SCREAMING_SNAKE_CASE ) ) UpperCamelCase = nn.Parameter(torch.ones(1 , _SCREAMING_SNAKE_CASE ) ) def A__ ( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = nn.Parameter(self.mean.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) UpperCamelCase = nn.Parameter(self.std.to(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) ) return self def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase = (embeds - self.mean) * 1.0 / self.std return embeds def A__ ( self , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase = (embeds * self.std) + self.mean return embeds
702
'''simple docstring''' import fire from utils import calculate_rouge, save_json def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , **__UpperCamelCase )-> int: UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()] UpperCamelCase = [x.strip() for x in open(__UpperCamelCase ).readlines()][: len(__UpperCamelCase )] UpperCamelCase = calculate_rouge(__UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) if save_path is not None: save_json(__UpperCamelCase , __UpperCamelCase , indent=__UpperCamelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
35
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class a_ ( lowerCamelCase ): lowercase = """dpt""" def __init__( self , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-12 , _SCREAMING_SNAKE_CASE=384 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[2, 5, 8, 11] , _SCREAMING_SNAKE_CASE="project" , _SCREAMING_SNAKE_CASE=[4, 2, 1, 0.5] , _SCREAMING_SNAKE_CASE=[96, 192, 384, 768] , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=-1 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.4 , _SCREAMING_SNAKE_CASE=255 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=[1, 1024, 24, 24] , _SCREAMING_SNAKE_CASE=[0, 1] , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = hidden_size UpperCamelCase = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("""Initializing the config with a `BiT` backbone.""" ) UpperCamelCase = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, } UpperCamelCase = BitConfig(**_SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): logger.info("""Initializing the config with a `BiT` backbone.""" ) UpperCamelCase = BitConfig(**_SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config else: raise ValueError( F"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) UpperCamelCase = backbone_featmap_shape UpperCamelCase = neck_ignore_stages if readout_type != "project": raise ValueError("""Readout type must be 'project' when using `DPT-hybrid` mode.""" ) else: UpperCamelCase = None UpperCamelCase = None UpperCamelCase = [] UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = qkv_bias UpperCamelCase = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("""Readout_type must be one of ['ignore', 'add', 'project']""" ) UpperCamelCase = readout_type UpperCamelCase = reassemble_factors UpperCamelCase = neck_hidden_sizes UpperCamelCase = fusion_hidden_size UpperCamelCase = head_in_index UpperCamelCase = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) UpperCamelCase = use_auxiliary_head UpperCamelCase = auxiliary_loss_weight UpperCamelCase = semantic_loss_ignore_index UpperCamelCase = semantic_classifier_dropout def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output
703
'''simple docstring''' from __future__ import annotations def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> tuple[float, list[float]]: UpperCamelCase = list(range(len(__UpperCamelCase ) ) ) UpperCamelCase = [v / w for v, w in zip(__UpperCamelCase , __UpperCamelCase )] index.sort(key=lambda __UpperCamelCase : ratio[i] , reverse=__UpperCamelCase ) UpperCamelCase = 0 UpperCamelCase = [0] * len(__UpperCamelCase ) for i in index: if weight[i] <= capacity: UpperCamelCase = 1 max_value += value[i] capacity -= weight[i] else: UpperCamelCase = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
35
0
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class a_ : @staticmethod def A__ ( *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" pass def lowercase__ ( __UpperCamelCase )-> str: UpperCamelCase = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def lowercase__ ( __UpperCamelCase )-> Dict: UpperCamelCase = np.array(__UpperCamelCase ) UpperCamelCase = npimg.shape return {"hash": hashimage(__UpperCamelCase ), "shape": shape} @is_pipeline_test @require_vision @require_torch class a_ ( unittest.TestCase ): lowercase = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) lowercase = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase = MaskGenerationPipeline(model=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" pass @require_tf @unittest.skip("""Image segmentation not implemented in TF""" ) def A__ ( self ) -> Union[str, Any]: """simple docstring""" pass @slow @require_torch def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = pipeline("""mask-generation""" , model="""facebook/sam-vit-huge""" ) UpperCamelCase = image_segmenter("""http://images.cocodataset.org/val2017/000000039769.jpg""" , points_per_batch=256 ) # Shortening by hashing UpperCamelCase = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(_SCREAMING_SNAKE_CASE ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0_4_4_4}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.0_2_1}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0_1_6_7}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0_1_3_2}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0_0_5_3}, {"""mask""": {"""hash""": """e2d0b7a0b7""", """shape""": (480, 640)}, """scores""": 0.9_9_6_7}, {"""mask""": {"""hash""": """453c7844bd""", """shape""": (480, 640)}, """scores""": 0.9_9_3}, {"""mask""": {"""hash""": """3d44f2926d""", """shape""": (480, 640)}, """scores""": 0.9_9_0_9}, {"""mask""": {"""hash""": """64033ddc3f""", """shape""": (480, 640)}, """scores""": 0.9_8_7_9}, {"""mask""": {"""hash""": """801064ff79""", """shape""": (480, 640)}, """scores""": 0.9_8_3_4}, {"""mask""": {"""hash""": """6172f276ef""", """shape""": (480, 640)}, """scores""": 0.9_7_1_6}, {"""mask""": {"""hash""": """b49e60e084""", """shape""": (480, 640)}, """scores""": 0.9_6_1_2}, {"""mask""": {"""hash""": """a811e775fd""", """shape""": (480, 640)}, """scores""": 0.9_5_9_9}, {"""mask""": {"""hash""": """a6a8ebcf4b""", """shape""": (480, 640)}, """scores""": 0.9_5_5_2}, {"""mask""": {"""hash""": """9d8257e080""", """shape""": (480, 640)}, """scores""": 0.9_5_3_2}, {"""mask""": {"""hash""": """32de6454a8""", """shape""": (480, 640)}, """scores""": 0.9_5_1_6}, {"""mask""": {"""hash""": """af3d4af2c8""", """shape""": (480, 640)}, """scores""": 0.9_4_9_9}, {"""mask""": {"""hash""": """3c6db475fb""", """shape""": (480, 640)}, """scores""": 0.9_4_8_3}, {"""mask""": {"""hash""": """c290813fb9""", """shape""": (480, 640)}, """scores""": 0.9_4_6_4}, {"""mask""": {"""hash""": """b6f0b8f606""", """shape""": (480, 640)}, """scores""": 0.9_4_3}, {"""mask""": {"""hash""": """92ce16bfdf""", """shape""": (480, 640)}, """scores""": 0.9_4_3}, {"""mask""": {"""hash""": """c749b25868""", """shape""": (480, 640)}, """scores""": 0.9_4_0_8}, {"""mask""": {"""hash""": """efb6cab859""", """shape""": (480, 640)}, """scores""": 0.9_3_3_5}, {"""mask""": {"""hash""": """1ff2eafb30""", """shape""": (480, 640)}, """scores""": 0.9_3_2_6}, {"""mask""": {"""hash""": """788b798e24""", """shape""": (480, 640)}, """scores""": 0.9_2_6_2}, {"""mask""": {"""hash""": """abea804f0e""", """shape""": (480, 640)}, """scores""": 0.8_9_9_9}, {"""mask""": {"""hash""": """7b9e8ddb73""", """shape""": (480, 640)}, """scores""": 0.8_9_8_6}, {"""mask""": {"""hash""": """cd24047c8a""", """shape""": (480, 640)}, """scores""": 0.8_9_8_4}, {"""mask""": {"""hash""": """6943e6bcbd""", """shape""": (480, 640)}, """scores""": 0.8_8_7_3}, {"""mask""": {"""hash""": """b5f47c9191""", """shape""": (480, 640)}, """scores""": 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = """facebook/sam-vit-huge""" UpperCamelCase = pipeline("""mask-generation""" , model=_SCREAMING_SNAKE_CASE ) UpperCamelCase = image_segmenter( """http://images.cocodataset.org/val2017/000000039769.jpg""" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing UpperCamelCase = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(_SCREAMING_SNAKE_CASE ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0_4_4_4}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.0_2_1_0}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0_1_6_7}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0_1_3_2}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0_0_5_3}, ] , )
704
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a_ ( lowerCamelCase ): lowercase = """deformable_detr""" lowercase = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase = backbone_config.get("""model_type""" ) UpperCamelCase = CONFIG_MAPPING[backbone_model_type] UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = use_timm_backbone UpperCamelCase = backbone_config UpperCamelCase = num_channels UpperCamelCase = num_queries UpperCamelCase = max_position_embeddings UpperCamelCase = d_model UpperCamelCase = encoder_ffn_dim UpperCamelCase = encoder_layers UpperCamelCase = encoder_attention_heads UpperCamelCase = decoder_ffn_dim UpperCamelCase = decoder_layers UpperCamelCase = decoder_attention_heads UpperCamelCase = dropout UpperCamelCase = attention_dropout UpperCamelCase = activation_dropout UpperCamelCase = activation_function UpperCamelCase = init_std UpperCamelCase = init_xavier_std UpperCamelCase = encoder_layerdrop UpperCamelCase = auxiliary_loss UpperCamelCase = position_embedding_type UpperCamelCase = backbone UpperCamelCase = use_pretrained_backbone UpperCamelCase = dilation # deformable attributes UpperCamelCase = num_feature_levels UpperCamelCase = encoder_n_points UpperCamelCase = decoder_n_points UpperCamelCase = two_stage UpperCamelCase = two_stage_num_proposals UpperCamelCase = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher UpperCamelCase = class_cost UpperCamelCase = bbox_cost UpperCamelCase = giou_cost # Loss coefficients UpperCamelCase = mask_loss_coefficient UpperCamelCase = dice_loss_coefficient UpperCamelCase = bbox_loss_coefficient UpperCamelCase = giou_loss_coefficient UpperCamelCase = eos_coefficient UpperCamelCase = focal_alpha UpperCamelCase = disable_custom_kernels super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def A__ ( self ) -> int: """simple docstring""" return self.d_model def A__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: UpperCamelCase = self.backbone_config.to_dict() UpperCamelCase = self.__class__.model_type return output
35
0