code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function: {act_fn}''' )
6
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = True def __init__( self :Optional[int] , **__A :str ) -> int: """simple docstring""" super().__init__(**__A ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE__ = kwargs.pop("""encoder""" ) SCREAMING_SNAKE_CASE__ = encoder_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""decoder""" ) SCREAMING_SNAKE_CASE__ = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = True @classmethod def _snake_case ( cls :str , __A :PretrainedConfig , __A :PretrainedConfig , **__A :List[str] ) -> PretrainedConfig: """simple docstring""" logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__A ) def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.encoder.to_dict() SCREAMING_SNAKE_CASE__ = self.decoder.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
6
1
import math def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = int(math.floor(math.sqrt(UpperCamelCase__ ) ) ) SCREAMING_SNAKE_CASE__ = 0 while arr[min(UpperCamelCase__ , UpperCamelCase__ ) - 1] < x: SCREAMING_SNAKE_CASE__ = step step += int(math.floor(math.sqrt(UpperCamelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: SCREAMING_SNAKE_CASE__ = prev + 1 if prev == min(UpperCamelCase__ , UpperCamelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": _lowerCamelCase = input('Enter numbers separated by a comma:\n').strip() _lowerCamelCase = [int(item) for item in user_input.split(',')] _lowerCamelCase = int(input('Enter the number to be searched:\n')) _lowerCamelCase = jump_search(arr, x) if res == -1: print('Number not found!') else: print(F'''Number {x} is at index {res}''')
6
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowerCamelCase_ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"text": Value("string" )} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "text" lowerCamelCase_ = "labels" def _snake_case ( self :Any , __A :Dict ) -> Optional[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] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :str ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
6
1
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar _lowerCamelCase = TypeVar('T') class UpperCamelCase_ ( Generic[T] ): def __init__( self :Optional[int] , __A :T ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = data SCREAMING_SNAKE_CASE__ = None def __str__( self :Any ) -> str: """simple docstring""" return f'''{self.data}''' class UpperCamelCase_ ( Generic[T] ): def __init__( self :List[Any] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = None def __iter__( self :Any ) -> Iterator[T]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.top while node: yield node.data SCREAMING_SNAKE_CASE__ = node.next def __str__( self :Dict ) -> str: """simple docstring""" return "->".join([str(__A ) for item in self] ) def __len__( self :List[Any] ) -> int: """simple docstring""" return len(tuple(iter(self ) ) ) def _snake_case ( self :List[Any] ) -> bool: """simple docstring""" return self.top is None def _snake_case ( self :Tuple , __A :T ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = Node(__A ) if not self.is_empty(): SCREAMING_SNAKE_CASE__ = self.top SCREAMING_SNAKE_CASE__ = node def _snake_case ( self :Dict ) -> T: """simple docstring""" if self.is_empty(): raise IndexError("""pop from empty stack""" ) assert isinstance(self.top , __A ) SCREAMING_SNAKE_CASE__ = self.top SCREAMING_SNAKE_CASE__ = self.top.next return pop_node.data def _snake_case ( self :Union[str, Any] ) -> T: """simple docstring""" if self.is_empty(): raise IndexError("""peek from empty stack""" ) assert self.top is not None return self.top.data def _snake_case ( self :List[Any] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if __name__ == "__main__": from doctest import testmod testmod()
6
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = model.config SCREAMING_SNAKE_CASE__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) SCREAMING_SNAKE_CASE__ = MBartConfig( is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , ) return encoder_config, decoder_config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if "encoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" ) if "decoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if name.startswith("""encoder""" ): if "layers" in name: SCREAMING_SNAKE_CASE__ = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "mask" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight""" if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias""" return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_split[3] ) SCREAMING_SNAKE_CASE__ = int(key_split[5] ) SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE__ = val[:dim, :] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ = val[-dim:, :] else: SCREAMING_SNAKE_CASE__ = val[:dim] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: SCREAMING_SNAKE_CASE__ = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): # load original model SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval() # load HuggingFace model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = original_model.state_dict() SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify results on scanned document SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" ) SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" SCREAMING_SNAKE_CASE__ = """When is the coffee break?""" SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>""" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: SCREAMING_SNAKE_CASE__ = """<s_cord>""" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": SCREAMING_SNAKE_CASE__ = """s_cord-v2>""" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>""" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt SCREAMING_SNAKE_CASE__ = """hello world""" else: raise ValueError("""Model name not supported""" ) SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[ """input_ids""" ] SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) # verify encoder hidden states SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) # verify decoder hidden states SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, 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 and processor to the 🤗 hub.', ) _lowerCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
6
1
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int | str] ): create_state_space_tree(UpperCamelCase__ , [] , 0 , [0 for i in range(len(UpperCamelCase__ ) )] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int | str] , UpperCamelCase__: list[int | str] , UpperCamelCase__: int , UpperCamelCase__: list[int] , ): if index == len(UpperCamelCase__ ): print(UpperCamelCase__ ) return for i in range(len(UpperCamelCase__ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) SCREAMING_SNAKE_CASE__ = True create_state_space_tree(UpperCamelCase__ , UpperCamelCase__ , index + 1 , UpperCamelCase__ ) current_sequence.pop() SCREAMING_SNAKE_CASE__ = False _lowerCamelCase = [3, 1, 2, 4] generate_all_permutations(sequence) _lowerCamelCase = ["A", "B", "C"] generate_all_permutations(sequence_a)
6
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_dpmpp_2m""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=7.5 , num_inference_steps=15 , output_type="""np""" , use_karras_sigmas=__A , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE__ = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE__ = n return int(UpperCamelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE__ = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE__ = n return int(UpperCamelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
6
1
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :int ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = (32, 32) SCREAMING_SNAKE_CASE__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__A ) return image @property def _snake_case ( self :str ) -> str: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) return model @property def _snake_case ( self :List[Any] ) -> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(__A ) @property def _snake_case ( self :Any ) -> Dict: """simple docstring""" def extract(*__A :Tuple , **__A :str ): class UpperCamelCase_ : def __init__( self :Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch.ones([0] ) def _snake_case ( self :Dict , __A :Tuple ) -> Any: """simple docstring""" self.pixel_values.to(__A ) return self return Out() return extract def _snake_case ( self :Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=__A , set_alpha_to_one=__A , ) SCREAMING_SNAKE_CASE__ = self.dummy_vae SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline( unet=__A , scheduler=__A , vae=__A , text_encoder=__A , tokenizer=__A , safety_checker=__A , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=__A , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ = PNDMScheduler(skip_prk_steps=__A ) SCREAMING_SNAKE_CASE__ = self.dummy_vae SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline( unet=__A , scheduler=__A , vae=__A , text_encoder=__A , tokenizer=__A , safety_checker=__A , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=__A , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=__A ) assert isinstance(__A , __A ) assert isinstance(pipe.scheduler , __A ) assert pipe.safety_checker is None SCREAMING_SNAKE_CASE__ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline.from_pretrained(__A ) # sanity check that the pipeline still works assert pipe.safety_checker is None SCREAMING_SNAKE_CASE__ = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dummy_cond_unet SCREAMING_SNAKE_CASE__ = PNDMScheduler(skip_prk_steps=__A ) SCREAMING_SNAKE_CASE__ = self.dummy_vae SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 SCREAMING_SNAKE_CASE__ = unet.half() SCREAMING_SNAKE_CASE__ = vae.half() SCREAMING_SNAKE_CASE__ = bert.half() # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline( unet=__A , scheduler=__A , vae=__A , text_encoder=__A , tokenizer=__A , safety_checker=__A , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :int ) -> Optional[int]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=__A ) SCREAMING_SNAKE_CASE__ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) SCREAMING_SNAKE_CASE__ = 40_0366_0346 SCREAMING_SNAKE_CASE__ = 7 # without safety guidance (sld_guidance_scale = 0) SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=__A , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=__A , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=__A ) SCREAMING_SNAKE_CASE__ = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = """padme amidala taking a bath artwork, safe for work, no nudity""" SCREAMING_SNAKE_CASE__ = 27_3497_1755 SCREAMING_SNAKE_CASE__ = 7 SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=__A , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=__A , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) SCREAMING_SNAKE_CASE__ = 10_4435_5234 SCREAMING_SNAKE_CASE__ = 12 SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=__A , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=__A , num_inference_steps=50 , output_type="""np""" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
6
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) )
6
1
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self :Union[str, Any] , __A :int = 3 , __A :int = 3 , __A :Tuple[str] = ("DownEncoderBlock2D",) , __A :Tuple[str] = ("UpDecoderBlock2D",) , __A :Tuple[int] = (64,) , __A :int = 1 , __A :str = "silu" , __A :int = 3 , __A :int = 32 , __A :int = 256 , __A :int = 32 , __A :Optional[int] = None , __A :float = 0.1_8_2_1_5 , __A :str = "group" , ) -> Any: """simple docstring""" super().__init__() # pass init params to Encoder SCREAMING_SNAKE_CASE__ = Encoder( in_channels=__A , out_channels=__A , down_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , double_z=__A , ) SCREAMING_SNAKE_CASE__ = vq_embed_dim if vq_embed_dim is not None else latent_channels SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = VectorQuantizer(__A , __A , beta=0.2_5 , remap=__A , sane_index_shape=__A ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) # pass init params to Decoder SCREAMING_SNAKE_CASE__ = Decoder( in_channels=__A , out_channels=__A , up_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , norm_type=__A , ) @apply_forward_hook def _snake_case ( self :Union[str, Any] , __A :torch.FloatTensor , __A :bool = True ) -> VQEncoderOutput: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.encoder(__A ) SCREAMING_SNAKE_CASE__ = self.quant_conv(__A ) if not return_dict: return (h,) return VQEncoderOutput(latents=__A ) @apply_forward_hook def _snake_case ( self :Tuple , __A :torch.FloatTensor , __A :bool = False , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" if not force_not_quantize: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = h SCREAMING_SNAKE_CASE__ = self.post_quant_conv(__A ) SCREAMING_SNAKE_CASE__ = self.decoder(__A , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=__A ) def _snake_case ( self :int , __A :torch.FloatTensor , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample SCREAMING_SNAKE_CASE__ = self.encode(__A ).latents SCREAMING_SNAKE_CASE__ = self.decode(__A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__A )
6
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""": """Friday""", """6""": """Saturday""", } SCREAMING_SNAKE_CASE__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(UpperCamelCase__ ) < 11: raise ValueError("""Must be 10 characters long""" ) # Get month SCREAMING_SNAKE_CASE__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("""Month must be between 1 - 12""" ) SCREAMING_SNAKE_CASE__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get day SCREAMING_SNAKE_CASE__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("""Date must be between 1 - 31""" ) # Get second separator SCREAMING_SNAKE_CASE__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get year SCREAMING_SNAKE_CASE__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8_500: raise ValueError( """Year out of range. There has to be some sort of limit...right?""" ) # Get datetime obj for validation SCREAMING_SNAKE_CASE__ = datetime.date(int(UpperCamelCase__ ) , int(UpperCamelCase__ ) , int(UpperCamelCase__ ) ) # Start math if m <= 2: SCREAMING_SNAKE_CASE__ = y - 1 SCREAMING_SNAKE_CASE__ = m + 12 # maths var SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[:2] ) SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[2:] ) SCREAMING_SNAKE_CASE__ = int(2.6 * m - 5.3_9 ) SCREAMING_SNAKE_CASE__ = int(c / 4 ) SCREAMING_SNAKE_CASE__ = int(k / 4 ) SCREAMING_SNAKE_CASE__ = int(d + k ) SCREAMING_SNAKE_CASE__ = int(t + u + v + x ) SCREAMING_SNAKE_CASE__ = int(z - (2 * c) ) SCREAMING_SNAKE_CASE__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" ) # Response SCREAMING_SNAKE_CASE__ = f'''Your date {date_input}, is a {days[str(UpperCamelCase__ )]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) _lowerCamelCase = parser.parse_args() zeller(args.date_input)
6
1
from typing import Any def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list ): if not input_list: return [] SCREAMING_SNAKE_CASE__ = [input_list.count(UpperCamelCase__ ) for value in input_list] SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(UpperCamelCase__ ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
6
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30522, type=int) _lowerCamelCase = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: _lowerCamelCase = pickle.load(fp) logger.info('Counting occurrences for MLM.') _lowerCamelCase = Counter() for tk_ids in data: counter.update(tk_ids) _lowerCamelCase = [0] * args.vocab_size for k, v in counter.items(): _lowerCamelCase = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: List[Any] ): global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: SCREAMING_SNAKE_CASE__ = mf_knapsack(i - 1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = max( mf_knapsack(i - 1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , mf_knapsack(i - 1 , UpperCamelCase__ , UpperCamelCase__ , j - wt[i - 1] ) + val[i - 1] , ) SCREAMING_SNAKE_CASE__ = val return f[i][j] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: str , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: SCREAMING_SNAKE_CASE__ = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: SCREAMING_SNAKE_CASE__ = dp[i - 1][w_] return dp[n][w_], dp def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: list , UpperCamelCase__: list ): if not (isinstance(UpperCamelCase__ , (list, tuple) ) and isinstance(UpperCamelCase__ , (list, tuple) )): raise ValueError( """Both the weights and values vectors must be either lists or tuples""" ) SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) if num_items != len(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = ( """The number of weights must be the same as the number of values.\n""" f'''But got {num_items} weights and {len(UpperCamelCase__ )} values''' ) raise ValueError(UpperCamelCase__ ) for i in range(UpperCamelCase__ ): if not isinstance(wt[i] , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = ( """All weights must be integers but got weight of """ f'''type {type(wt[i] )} at index {i}''' ) raise TypeError(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = knapsack(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = set() _construct_solution(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return optimal_val, example_optional_set def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list , UpperCamelCase__: list , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: set ): # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(UpperCamelCase__ , UpperCamelCase__ , i - 1 , UpperCamelCase__ , UpperCamelCase__ ) else: optimal_set.add(UpperCamelCase__ ) _construct_solution(UpperCamelCase__ , UpperCamelCase__ , i - 1 , j - wt[i - 1] , UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = [3, 2, 4, 4] _lowerCamelCase = [4, 3, 2, 3] _lowerCamelCase = 4 _lowerCamelCase = 6 _lowerCamelCase = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] _lowerCamelCase , _lowerCamelCase = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 _lowerCamelCase , _lowerCamelCase = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('optimal_value = ', optimal_solution) print('An optimal subset corresponding to the optimal value', optimal_subset)
6
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
1
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '▁' _lowerCamelCase = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } _lowerCamelCase = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } _lowerCamelCase = { 'facebook/s2t-small-librispeech-asr': 1024, } _lowerCamelCase = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] _lowerCamelCase = {'mustc': MUSTC_LANGS} class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = MAX_MODEL_INPUT_SIZES lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = [] def __init__( self :Union[str, Any] , __A :Dict , __A :Tuple , __A :List[str]="<s>" , __A :str="</s>" , __A :List[str]="<pad>" , __A :Union[str, Any]="<unk>" , __A :List[Any]=False , __A :Tuple=False , __A :Optional[int]=None , __A :Dict=None , __A :Optional[Dict[str, Any]] = None , **__A :int , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , pad_token=__A , do_upper_case=__A , do_lower_case=__A , tgt_lang=__A , lang_codes=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) SCREAMING_SNAKE_CASE__ = do_upper_case SCREAMING_SNAKE_CASE__ = do_lower_case SCREAMING_SNAKE_CASE__ = load_json(__A ) SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE__ = spm_file SCREAMING_SNAKE_CASE__ = load_spm(__A , self.sp_model_kwargs ) if lang_codes is not None: SCREAMING_SNAKE_CASE__ = lang_codes SCREAMING_SNAKE_CASE__ = LANGUAGES[lang_codes] SCREAMING_SNAKE_CASE__ = [f'''<lang:{lang}>''' for lang in self.langs] SCREAMING_SNAKE_CASE__ = {lang: self.sp_model.PieceToId(f'''<lang:{lang}>''' ) for lang in self.langs} SCREAMING_SNAKE_CASE__ = self.lang_tokens SCREAMING_SNAKE_CASE__ = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: SCREAMING_SNAKE_CASE__ = {} @property def _snake_case ( self :Dict ) -> int: """simple docstring""" return len(self.encoder ) @property def _snake_case ( self :str ) -> str: """simple docstring""" return self._tgt_lang @tgt_lang.setter def _snake_case ( self :List[Any] , __A :Optional[int] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = new_tgt_lang self.set_tgt_lang_special_tokens(__A ) def _snake_case ( self :Union[str, Any] , __A :str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[tgt_lang] SCREAMING_SNAKE_CASE__ = [lang_code_id] def _snake_case ( self :Optional[int] , __A :str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__A , out_type=__A ) def _snake_case ( self :List[Any] , __A :Optional[Any] ) -> Any: """simple docstring""" return self.encoder.get(__A , self.encoder[self.unk_token] ) def _snake_case ( self :List[Any] , __A :int ) -> str: """simple docstring""" return self.decoder.get(__A , self.unk_token ) def _snake_case ( self :str , __A :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: SCREAMING_SNAKE_CASE__ = self.sp_model.decode(__A ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " SCREAMING_SNAKE_CASE__ = [] else: current_sub_tokens.append(__A ) SCREAMING_SNAKE_CASE__ = self.sp_model.decode(__A ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def _snake_case ( self :Any , __A :Optional[int] , __A :Dict=None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id] def _snake_case ( self :int , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__A )) + suffix_ones return prefix_ones + ([0] * len(__A )) + ([0] * len(__A )) + suffix_ones def _snake_case ( self :str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self :Dict ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.__dict__.copy() SCREAMING_SNAKE_CASE__ = None return state def __setstate__( self :Tuple , __A :Dict ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = load_spm(self.spm_file , self.sp_model_kwargs ) def _snake_case ( self :Dict , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Path(__A ) assert save_dir.is_dir(), f'''{save_directory} should be a directory''' SCREAMING_SNAKE_CASE__ = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""] ) save_json(self.encoder , __A ) if os.path.abspath(self.spm_file ) != os.path.abspath(__A ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __A ) elif not os.path.isfile(self.spm_file ): with open(__A , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() fi.write(__A ) return (str(__A ), str(__A )) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Dict[str, Any] ): SCREAMING_SNAKE_CASE__ = sentencepiece.SentencePieceProcessor(**UpperCamelCase__ ) spm.Load(str(UpperCamelCase__ ) ) return spm def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): with open(UpperCamelCase__ , """r""" ) as f: return json.load(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: str ): with open(UpperCamelCase__ , """w""" ) as f: json.dump(UpperCamelCase__ , UpperCamelCase__ , indent=2 )
6
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "OwlViTImageProcessor" lowerCamelCase_ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self :Optional[Any] , __A :int=None , __A :Optional[int]=None , **__A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :str , __A :Dict=None , __A :List[str]=None , __A :str=None , __A :Optional[int]="max_length" , __A :Tuple="np" , **__A :int ) -> Tuple: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(__A , __A ) or (isinstance(__A , __A ) and not isinstance(text[0] , __A )): SCREAMING_SNAKE_CASE__ = [self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )] elif isinstance(__A , __A ) and isinstance(text[0] , __A ): SCREAMING_SNAKE_CASE__ = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ = max([len(__A ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(__A ) != max_num_queries: SCREAMING_SNAKE_CASE__ = t + [""" """] * (max_num_queries - len(__A )) SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , padding=__A , return_tensors=__A , **__A ) encodings.append(__A ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = input_ids SCREAMING_SNAKE_CASE__ = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = self.image_processor( __A , return_tensors=__A , **__A ).pixel_values SCREAMING_SNAKE_CASE__ = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Dict , **__A :Dict ) -> Optional[int]: """simple docstring""" return self.image_processor.post_process(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Dict , **__A :List[str] ) -> Optional[Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*__A , **__A ) def _snake_case ( self :str , *__A :List[str] , **__A :Union[str, Any] ) -> Any: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*__A , **__A ) def _snake_case ( self :Dict , *__A :List[str] , **__A :List[str] ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Dict , *__A :Dict , **__A :List[str] ) -> str: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class @property def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __A , ) return self.image_processor
6
1
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) )
6
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self :Union[str, Any] , __A :int = 3 , __A :int = 3 , __A :Tuple[str] = ("DownEncoderBlock2D",) , __A :Tuple[str] = ("UpDecoderBlock2D",) , __A :Tuple[int] = (64,) , __A :int = 1 , __A :str = "silu" , __A :int = 3 , __A :int = 32 , __A :int = 256 , __A :int = 32 , __A :Optional[int] = None , __A :float = 0.1_8_2_1_5 , __A :str = "group" , ) -> Any: """simple docstring""" super().__init__() # pass init params to Encoder SCREAMING_SNAKE_CASE__ = Encoder( in_channels=__A , out_channels=__A , down_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , double_z=__A , ) SCREAMING_SNAKE_CASE__ = vq_embed_dim if vq_embed_dim is not None else latent_channels SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = VectorQuantizer(__A , __A , beta=0.2_5 , remap=__A , sane_index_shape=__A ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) # pass init params to Decoder SCREAMING_SNAKE_CASE__ = Decoder( in_channels=__A , out_channels=__A , up_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , norm_type=__A , ) @apply_forward_hook def _snake_case ( self :Union[str, Any] , __A :torch.FloatTensor , __A :bool = True ) -> VQEncoderOutput: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.encoder(__A ) SCREAMING_SNAKE_CASE__ = self.quant_conv(__A ) if not return_dict: return (h,) return VQEncoderOutput(latents=__A ) @apply_forward_hook def _snake_case ( self :Tuple , __A :torch.FloatTensor , __A :bool = False , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" if not force_not_quantize: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = h SCREAMING_SNAKE_CASE__ = self.post_quant_conv(__A ) SCREAMING_SNAKE_CASE__ = self.decoder(__A , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=__A ) def _snake_case ( self :int , __A :torch.FloatTensor , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample SCREAMING_SNAKE_CASE__ = self.encode(__A ).latents SCREAMING_SNAKE_CASE__ = self.decode(__A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__A )
6
1
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = model.config SCREAMING_SNAKE_CASE__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) SCREAMING_SNAKE_CASE__ = MBartConfig( is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , ) return encoder_config, decoder_config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if "encoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" ) if "decoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if name.startswith("""encoder""" ): if "layers" in name: SCREAMING_SNAKE_CASE__ = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "mask" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight""" if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias""" return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_split[3] ) SCREAMING_SNAKE_CASE__ = int(key_split[5] ) SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE__ = val[:dim, :] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ = val[-dim:, :] else: SCREAMING_SNAKE_CASE__ = val[:dim] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: SCREAMING_SNAKE_CASE__ = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): # load original model SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval() # load HuggingFace model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = original_model.state_dict() SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify results on scanned document SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" ) SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" SCREAMING_SNAKE_CASE__ = """When is the coffee break?""" SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>""" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: SCREAMING_SNAKE_CASE__ = """<s_cord>""" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": SCREAMING_SNAKE_CASE__ = """s_cord-v2>""" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>""" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt SCREAMING_SNAKE_CASE__ = """hello world""" else: raise ValueError("""Model name not supported""" ) SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[ """input_ids""" ] SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) # verify encoder hidden states SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) # verify decoder hidden states SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, 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 and processor to the 🤗 hub.', ) _lowerCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
6
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = jnp.floataa lowerCamelCase_ = True def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = nn.Dense(5 , dtype=self.dtype ) def __call__( self :List[Any] , *__A :int , **__A :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super().__call__(*__A , **__A ) SCREAMING_SNAKE_CASE__ = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = FlaxBigBirdForNaturalQuestionsModule def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): def cross_entropy(UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=None ): SCREAMING_SNAKE_CASE__ = logits.shape[-1] SCREAMING_SNAKE_CASE__ = (labels[..., None] == jnp.arange(UpperCamelCase__ )[None]).astype("""f4""" ) SCREAMING_SNAKE_CASE__ = jax.nn.log_softmax(UpperCamelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE__ = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: SCREAMING_SNAKE_CASE__ = reduction(UpperCamelCase__ ) return loss SCREAMING_SNAKE_CASE__ = partial(UpperCamelCase__ , reduction=jnp.mean ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class UpperCamelCase_ : lowerCamelCase_ = "google/bigbird-roberta-base" lowerCamelCase_ = 30_00 lowerCamelCase_ = 1_05_00 lowerCamelCase_ = 1_28 lowerCamelCase_ = 3 lowerCamelCase_ = 1 lowerCamelCase_ = 5 # tx_args lowerCamelCase_ = 3e-5 lowerCamelCase_ = 0.0 lowerCamelCase_ = 2_00_00 lowerCamelCase_ = 0.0095 lowerCamelCase_ = "bigbird-roberta-natural-questions" lowerCamelCase_ = "training-expt" lowerCamelCase_ = "data/nq-training.jsonl" lowerCamelCase_ = "data/nq-validation.jsonl" def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(self.base_dir , self.save_dir ) SCREAMING_SNAKE_CASE__ = self.batch_size_per_device * jax.device_count() @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 40_96 # no dynamic padding on TPUs def __call__( self :Optional[Any] , __A :Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.collate_fn(__A ) SCREAMING_SNAKE_CASE__ = jax.tree_util.tree_map(__A , __A ) return batch def _snake_case ( self :List[Any] , __A :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.fetch_inputs(features["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = { """input_ids""": jnp.array(__A , dtype=jnp.intaa ), """attention_mask""": jnp.array(__A , dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ), } return batch def _snake_case ( self :Tuple , __A :list ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self._fetch_inputs(__A ) for ids in input_ids] return zip(*__A ) def _snake_case ( self :List[str] , __A :list ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [1 for _ in range(len(__A ) )] while len(__A ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=None ): if seed is not None: SCREAMING_SNAKE_CASE__ = dataset.shuffle(seed=UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) // batch_size ): SCREAMING_SNAKE_CASE__ = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase__ ) @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] , **UpperCamelCase__: Optional[int] ): def loss_fn(UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=UpperCamelCase__ , dropout_rng=UpperCamelCase__ , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs return state.loss_fn( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = jax.random.split(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.value_and_grad(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = grad_fn(state.params ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean(UpperCamelCase__ , """batch""" ) SCREAMING_SNAKE_CASE__ = state.apply_gradients(grads=UpperCamelCase__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , **UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=state.params , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs SCREAMING_SNAKE_CASE__ = state.loss_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class UpperCamelCase_ ( train_state.TrainState ): lowerCamelCase_ = struct.field(pytree_node=UpperCamelCase__ ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None def _snake_case ( self :List[Any] , __A :str , __A :str , __A :str , __A :Tuple=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = model.params SCREAMING_SNAKE_CASE__ = TrainState.create( apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , ) if ckpt_dir is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = restore_checkpoint(__A , __A ) SCREAMING_SNAKE_CASE__ = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = build_tx(**__A ) SCREAMING_SNAKE_CASE__ = train_state.TrainState( step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = data_collator SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = jax_utils.replicate(__A ) return state def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :int , __A :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.args SCREAMING_SNAKE_CASE__ = len(__A ) // args.batch_size SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ = jax.random.split(__A , jax.device_count() ) for epoch in range(args.max_epochs ): SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , args.batch_size , seed=__A ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc=f'''Running EPOCH-{epoch}''' ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.train_step_fn(__A , __A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(state.step ) SCREAMING_SNAKE_CASE__ = running_loss.item() / i SCREAMING_SNAKE_CASE__ = self.scheduler_fn(state_step - 1 ) SCREAMING_SNAKE_CASE__ = self.evaluate(__A , __A ) SCREAMING_SNAKE_CASE__ = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(__A ) ) self.logger.log(__A , commit=__A ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__A ) def _snake_case ( self :List[str] , __A :Dict , __A :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , self.args.batch_size ) SCREAMING_SNAKE_CASE__ = len(__A ) // self.args.batch_size SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc="""Evaluating ... """ ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ = self.val_step_fn(__A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _snake_case ( self :List[Any] , __A :Any , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(__A ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=""" ... """ ) self.model_save_fn(__A , params=state.params ) with open(os.path.join(__A , """opt_state.msgpack""" ) , """wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__A , """args.joblib""" ) ) joblib.dump(self.data_collator , os.path.join(__A , """data_collator.joblib""" ) ) with open(os.path.join(__A , """training_state.json""" ) , """w""" ) as f: json.dump({"""step""": state.step.item()} , __A ) print("""DONE""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=""" ... """ ) with open(os.path.join(UpperCamelCase__ , """flax_model.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase__ , """opt_state.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.opt_state , f.read() ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """args.joblib""" ) ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """data_collator.joblib""" ) ) with open(os.path.join(UpperCamelCase__ , """training_state.json""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = num_train_steps - warmup_steps SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=UpperCamelCase__ , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=1e-7 , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): def weight_decay_mask(UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = traverse_util.flatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = scheduler_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.adamw(learning_rate=UpperCamelCase__ , weight_decay=UpperCamelCase__ , mask=UpperCamelCase__ ) return tx, lr
6
1
_lowerCamelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] ): # Return True if there is node that has not iterated. SCREAMING_SNAKE_CASE__ = [False] * len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [s] SCREAMING_SNAKE_CASE__ = True while queue: SCREAMING_SNAKE_CASE__ = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = u return visited[t] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [-1] * (len(UpperCamelCase__ )) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [i[:] for i in graph] # Record original cut, copy. while bfs(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = float("""Inf""" ) SCREAMING_SNAKE_CASE__ = sink while s != source: # Find the minimum value in select path SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ , graph[parent[s]][s] ) SCREAMING_SNAKE_CASE__ = parent[s] max_flow += path_flow SCREAMING_SNAKE_CASE__ = sink while v != source: SCREAMING_SNAKE_CASE__ = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow SCREAMING_SNAKE_CASE__ = parent[v] for i in range(len(UpperCamelCase__ ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
6
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function: {act_fn}''' )
6
1
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed _lowerCamelCase = { 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: int ): if args.student_type == "roberta": SCREAMING_SNAKE_CASE__ = False elif args.student_type == "gpt2": SCREAMING_SNAKE_CASE__ = False def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: int ): if args.student_type == "roberta": SCREAMING_SNAKE_CASE__ = False def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=UpperCamelCase__ , choices=["""distilbert""", """roberta""", """gpt2"""] , required=UpperCamelCase__ , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=UpperCamelCase__ , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=UpperCamelCase__ , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=UpperCamelCase__ , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=UpperCamelCase__ , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=UpperCamelCase__ , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=UpperCamelCase__ , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=UpperCamelCase__ , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.1_5 , type=UpperCamelCase__ , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=UpperCamelCase__ , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=UpperCamelCase__ , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=UpperCamelCase__ , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=UpperCamelCase__ , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=UpperCamelCase__ , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=UpperCamelCase__ , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=UpperCamelCase__ , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=UpperCamelCase__ , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.0_5 , type=UpperCamelCase__ , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=UpperCamelCase__ , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5e-4 , type=UpperCamelCase__ , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1e-6 , type=UpperCamelCase__ , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=UpperCamelCase__ , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.0_2 , type=UpperCamelCase__ , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=UpperCamelCase__ , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=UpperCamelCase__ , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=UpperCamelCase__ , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=UpperCamelCase__ , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=UpperCamelCase__ , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=UpperCamelCase__ , default=4_000 , help="""Checkpoint interval.""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args() sanity_checks(UpperCamelCase__ ) # ARGS # init_gpu_params(UpperCamelCase__ ) set_seed(UpperCamelCase__ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite''' """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f'''Experiment will be dumped and logged in {args.dump_path}''' ) # SAVE PARAMS # logger.info(f'''Param: {args}''' ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(UpperCamelCase__ ) , UpperCamelCase__ , indent=4 ) git_log(args.dump_path ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = MODEL_CLASSES[args.student_type] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # SCREAMING_SNAKE_CASE__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) SCREAMING_SNAKE_CASE__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): SCREAMING_SNAKE_CASE__ = tokenizer.all_special_tokens.index(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tokenizer.all_special_ids[idx] logger.info(f'''Special tokens {special_tok_ids}''' ) SCREAMING_SNAKE_CASE__ = special_tok_ids SCREAMING_SNAKE_CASE__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f'''Loading data from {args.data_file}''' ) with open(args.data_file , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ ) if args.mlm: logger.info(f'''Loading token counts from {args.token_counts} (already pre-computed)''' ) with open(args.token_counts , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.maximum(UpperCamelCase__ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): SCREAMING_SNAKE_CASE__ = 0.0 # do not predict special tokens SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = LmSeqsDataset(params=UpperCamelCase__ , data=UpperCamelCase__ ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f'''Loading student config from {args.student_config}''' ) SCREAMING_SNAKE_CASE__ = student_config_class.from_pretrained(args.student_config ) SCREAMING_SNAKE_CASE__ = True if args.student_pretrained_weights is not None: logger.info(f'''Loading pretrained weights from {args.student_pretrained_weights}''' ) SCREAMING_SNAKE_CASE__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = student_model_class(UpperCamelCase__ ) if args.n_gpu > 0: student.to(f'''cuda:{args.local_rank}''' ) logger.info("""Student loaded.""" ) # TEACHER # SCREAMING_SNAKE_CASE__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=UpperCamelCase__ ) if args.n_gpu > 0: teacher.to(f'''cuda:{args.local_rank}''' ) logger.info(f'''Teacher loaded from {args.teacher_name}.''' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(UpperCamelCase__ , UpperCamelCase__ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(UpperCamelCase__ , UpperCamelCase__ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() SCREAMING_SNAKE_CASE__ = Distiller( params=UpperCamelCase__ , dataset=UpperCamelCase__ , token_probs=UpperCamelCase__ , student=UpperCamelCase__ , teacher=UpperCamelCase__ ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
6
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = SwinConfig.from_pretrained( """microsoft/swin-tiny-patch4-window7-224""" , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) SCREAMING_SNAKE_CASE__ = MaskFormerConfig(backbone_config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" if "ade20k-full" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 847 SCREAMING_SNAKE_CASE__ = """maskformer-ade20k-full-id2label.json""" elif "ade" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 150 SCREAMING_SNAKE_CASE__ = """ade20k-id2label.json""" elif "coco-stuff" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 171 SCREAMING_SNAKE_CASE__ = """maskformer-coco-stuff-id2label.json""" elif "coco" in model_name: # TODO SCREAMING_SNAKE_CASE__ = 133 SCREAMING_SNAKE_CASE__ = """coco-panoptic-id2label.json""" elif "cityscapes" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 19 SCREAMING_SNAKE_CASE__ = """cityscapes-id2label.json""" elif "vistas" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 65 SCREAMING_SNAKE_CASE__ = """mapillary-vistas-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [] # stem # fmt: off rename_keys.append(("""backbone.patch_embed.proj.weight""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.proj.bias""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """model.pixel_level_module.encoder.model.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """model.pixel_level_module.encoder.model.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.layers.{i}.downsample.reduction.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(("""sem_seg_head.layer_4.weight""", """model.pixel_level_module.decoder.fpn.stem.0.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.weight""", """model.pixel_level_module.decoder.fpn.stem.1.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.bias""", """model.pixel_level_module.decoder.fpn.stem.1.bias""") ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((f'''sem_seg_head.adapter_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(("""sem_seg_head.mask_features.weight""", """model.pixel_level_module.decoder.mask_projection.weight""") ) rename_keys.append(("""sem_seg_head.mask_features.bias""", """model.pixel_level_module.decoder.mask_projection.bias""") ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.weight""", """model.transformer_module.decoder.layernorm.weight""") ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.bias""", """model.transformer_module.decoder.layernorm.bias""") ) # heads on top rename_keys.append(("""sem_seg_head.predictor.query_embed.weight""", """model.transformer_module.queries_embedder.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.weight""", """model.transformer_module.input_projection.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.bias""", """model.transformer_module.input_projection.bias""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.weight""", """class_predictor.weight""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.bias""", """class_predictor.bias""") ) for i in range(3 ): rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', f'''mask_embedder.{i}.0.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', f'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE__ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[: dim] SCREAMING_SNAKE_CASE__ = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-dim :] # fmt: on def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): # fmt: off SCREAMING_SNAKE_CASE__ = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # fmt: on def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: bool = False ): SCREAMING_SNAKE_CASE__ = get_maskformer_config(UpperCamelCase__ ) # load original state_dict with open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = data["""model"""] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys SCREAMING_SNAKE_CASE__ = create_rename_keys(UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) read_in_swin_q_k_v(UpperCamelCase__ , config.backbone_config ) read_in_decoder_q_k_v(UpperCamelCase__ , UpperCamelCase__ ) # update to torch tensors for key, value in state_dict.items(): SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) # load 🤗 model SCREAMING_SNAKE_CASE__ = MaskFormerForInstanceSegmentation(UpperCamelCase__ ) model.eval() for name, param in model.named_parameters(): print(UpperCamelCase__ , param.shape ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(UpperCamelCase__ ) == 0, f'''Unexpected keys: {unexpected_keys}''' # verify results SCREAMING_SNAKE_CASE__ = prepare_img() if "vistas" in model_name: SCREAMING_SNAKE_CASE__ = 65 elif "cityscapes" in model_name: SCREAMING_SNAKE_CASE__ = 65_535 else: SCREAMING_SNAKE_CASE__ = 255 SCREAMING_SNAKE_CASE__ = True if """ade""" in model_name else False SCREAMING_SNAKE_CASE__ = MaskFormerImageProcessor(ignore_index=UpperCamelCase__ , reduce_labels=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(UpperCamelCase__ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = model(**UpperCamelCase__ ) print("""Logits:""" , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": SCREAMING_SNAKE_CASE__ = torch.tensor( [[3.6_3_5_3, -4.4_7_7_0, -2.6_0_6_5], [0.5_0_8_1, -4.2_3_9_4, -3.5_3_4_3], [2.1_9_0_9, -5.0_3_5_3, -1.9_3_2_3]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: print("""Pushing model and image processor to the hub...""" ) model.push_to_hub(f'''nielsr/{model_name}''' ) image_processor.push_to_hub(f'''nielsr/{model_name}''' ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='maskformer-swin-tiny-ade', type=str, help=('Name of the MaskFormer model you\'d like to convert',), ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl', type=str, help='Path to the original state dict (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, 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.' ) _lowerCamelCase = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
6
1
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging _lowerCamelCase = logging.get_logger(__name__) logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str ): if "xprophetnet" in prophetnet_checkpoint_path: SCREAMING_SNAKE_CASE__ = XLMProphetNetForConditionalGenerationOld.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = XLMProphetNetForConditionalGeneration.from_pretrained( UpperCamelCase__ , output_loading_info=UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = ProphetNetForConditionalGenerationOld.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = ProphetNetForConditionalGeneration.from_pretrained( UpperCamelCase__ , output_loading_info=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = ["""key_proj""", """value_proj""", """query_proj"""] SCREAMING_SNAKE_CASE__ = { """self_attn""": """ngram_self_attn""", """cross_attn""": """encoder_attn""", """cross_attn_layer_norm""": """encoder_attn_layer_norm""", """feed_forward_layer_norm""": """final_layer_norm""", """feed_forward""": """""", """intermediate""": """fc1""", """output""": """fc2""", """key_proj""": """k_proj""", """query_proj""": """q_proj""", """value_proj""": """v_proj""", """word_embeddings""": """embed_tokens""", """embeddings_layer_norm""": """emb_layer_norm""", """relative_pos_embeddings""": """relative_linear""", """ngram_embeddings""": """ngram_input_embed""", """position_embeddings""": """embed_positions""", } for key in loading_info["missing_keys"]: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) if attributes[0] == "lm_head": SCREAMING_SNAKE_CASE__ = prophet SCREAMING_SNAKE_CASE__ = prophet_old else: SCREAMING_SNAKE_CASE__ = prophet.prophetnet SCREAMING_SNAKE_CASE__ = prophet_old.model SCREAMING_SNAKE_CASE__ = False for attribute in attributes: if attribute in mapping: SCREAMING_SNAKE_CASE__ = mapping[attribute] if not hasattr(UpperCamelCase__ , UpperCamelCase__ ) and len(UpperCamelCase__ ) > 0: SCREAMING_SNAKE_CASE__ = attribute elif hasattr(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" SCREAMING_SNAKE_CASE__ = old_model.weight logger.info(f'''{attribute} is initialized.''' ) SCREAMING_SNAKE_CASE__ = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" SCREAMING_SNAKE_CASE__ = old_model.bias logger.info(f'''{attribute} is initialized''' ) SCREAMING_SNAKE_CASE__ = True break elif attribute in special_keys and hasattr(UpperCamelCase__ , """in_proj_weight""" ): SCREAMING_SNAKE_CASE__ = old_model.in_proj_weight.shape[0] // 3 SCREAMING_SNAKE_CASE__ = getattr(UpperCamelCase__ , UpperCamelCase__ ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": SCREAMING_SNAKE_CASE__ = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) SCREAMING_SNAKE_CASE__ = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": SCREAMING_SNAKE_CASE__ = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) SCREAMING_SNAKE_CASE__ = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": SCREAMING_SNAKE_CASE__ = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) SCREAMING_SNAKE_CASE__ = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) SCREAMING_SNAKE_CASE__ = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 512, "We want 512 position_embeddings." SCREAMING_SNAKE_CASE__ = nn.Parameter(old_model.embed_positions.weight[:512, :] ) SCREAMING_SNAKE_CASE__ = True break if attribute.isdigit(): SCREAMING_SNAKE_CASE__ = model[int(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ = old_model[int(UpperCamelCase__ )] else: SCREAMING_SNAKE_CASE__ = getattr(UpperCamelCase__ , UpperCamelCase__ ) if old_attribute == "": SCREAMING_SNAKE_CASE__ = old_model else: if not hasattr(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError(f'''{old_model} does not have {old_attribute}''' ) SCREAMING_SNAKE_CASE__ = getattr(UpperCamelCase__ , UpperCamelCase__ ) if not is_key_init: raise ValueError(f'''{key} was not correctly initialized!''' ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) prophet.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--prophetnet_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
6
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCamelCase = 1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py _lowerCamelCase = 0 _lowerCamelCase = 0XE0_00 _lowerCamelCase = 0XE0_01 _lowerCamelCase = 0XE0_02 _lowerCamelCase = 0XE0_03 _lowerCamelCase = 0XE0_04 # Maps special codepoints to human-readable names. _lowerCamelCase = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. _lowerCamelCase = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self :str , __A :str=chr(__A ) , __A :str=chr(__A ) , __A :Dict=chr(__A ) , __A :str=chr(__A ) , __A :Union[str, Any]=chr(__A ) , __A :str=chr(__A ) , __A :int=False , __A :int=2048 , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , model_max_length=__A , **__A , ) # Creates a mapping for looking up the IDs of special symbols. SCREAMING_SNAKE_CASE__ = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): SCREAMING_SNAKE_CASE__ = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. SCREAMING_SNAKE_CASE__ = { codepoint: name for name, codepoint in self._special_codepoints.items() } SCREAMING_SNAKE_CASE__ = UNICODE_VOCAB_SIZE SCREAMING_SNAKE_CASE__ = len(self._special_codepoints ) @property def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" return self._unicode_vocab_size def _snake_case ( self :Tuple , __A :str ) -> List[str]: """simple docstring""" return list(__A ) def _snake_case ( self :Optional[Any] , __A :str ) -> int: """simple docstring""" try: return ord(__A ) except TypeError: raise ValueError(f'''invalid token: \'{token}\'''' ) def _snake_case ( self :str , __A :int ) -> str: """simple docstring""" try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(__A ) except TypeError: raise ValueError(f'''invalid id: {index}''' ) def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Any: """simple docstring""" return "".join(__A ) def _snake_case ( self :Optional[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] + ([0] * len(__A )) + [1] if token_ids_a is not None: result += ([0] * len(__A )) + [1] return result def _snake_case ( self :List[str] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Any: """simple docstring""" return ()
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ = True for i in range(UpperCamelCase__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: SCREAMING_SNAKE_CASE__ = True if a[i].islower(): SCREAMING_SNAKE_CASE__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
6
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) _lowerCamelCase = 'bert-base-cased' _lowerCamelCase = 'fp16' _lowerCamelCase = 'bf16' _lowerCamelCase = [FPaa, BFaa] @require_fsdp @require_cuda class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = dict( ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , ) def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = f'''{i + 1}''' SCREAMING_SNAKE_CASE__ = strategy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def _snake_case ( self :int ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = prefetch_policy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = state_dict_type with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoModel.from_pretrained(__A ) for policy in FSDP_AUTO_WRAP_POLICY: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = policy if policy == "TRANSFORMER_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """BertLayer""" elif policy == "SIZE_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """2000""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """TRANSFORMER_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """T5Layer""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() with self.assertRaises(__A ) as cm: fsdp_plugin.set_auto_wrap_policy(__A ) self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """SIZE_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """0""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = mp_dtype with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = Accelerator() if mp_dtype == "fp16": SCREAMING_SNAKE_CASE__ = torch.floataa elif mp_dtype == "bf16": SCREAMING_SNAKE_CASE__ = torch.bfloataa SCREAMING_SNAKE_CASE__ = MixedPrecision(param_dtype=__A , reduce_dtype=__A , buffer_dtype=__A ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __A ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , __A ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__A ) def _snake_case ( self :str ) -> str: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = str(__A ).lower() with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__A ) ) @require_fsdp @require_multi_gpu @slow class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Any ) -> Any: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = 0.8_2 SCREAMING_SNAKE_CASE__ = [ """fsdp_shard_grad_op_transformer_based_wrap""", """fsdp_full_shard_transformer_based_wrap""", ] SCREAMING_SNAKE_CASE__ = { """multi_gpu_fp16""": 3200, """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2000, """fsdp_full_shard_transformer_based_wrap_fp16""": 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] ) def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_performance.py""" ) SCREAMING_SNAKE_CASE__ = ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""] for config in self.performance_configs: SCREAMING_SNAKE_CASE__ = cmd.copy() for i, strategy in enumerate(__A ): if strategy.lower() in config: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "fp32" in config: cmd_config.append("""--mixed_precision=no""" ) else: cmd_config.append("""--mixed_precision=fp16""" ) if "cpu_offload" in config: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--performance_lower_bound={self.performance_lower_bound}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_checkpointing.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp""", """--mixed_precision=fp16""", """--fsdp_transformer_layer_cls_to_wrap=BertLayer""", ] for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = cmd.copy() cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) if strategy != "FULL_SHARD": continue SCREAMING_SNAKE_CASE__ = len(__A ) for state_dict_type in FSDP_STATE_DICT_TYPE: SCREAMING_SNAKE_CASE__ = cmd_config[:state_dict_config_index] cmd_config.append(f'''--fsdp_state_dict_type={state_dict_type}''' ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', """--partial_train_epoch=1""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) SCREAMING_SNAKE_CASE__ = cmd_config[:-1] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdir , """epoch_0""" ) cmd_config.extend( [ f'''--resume_from_checkpoint={resume_from_checkpoint}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): SCREAMING_SNAKE_CASE__ = cmd.copy() if "fp16" in spec: cmd_config.extend(["""--mixed_precision=fp16"""] ) else: cmd_config.extend(["""--mixed_precision=no"""] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["""--use_fsdp"""] ) for i, strategy in enumerate(__A ): if strategy.lower() in spec: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "cpu_offload" in spec: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--peak_memory_upper_bound={peak_mem_upper_bound}''', f'''--n_train={self.n_train}''', f'''--n_val={self.n_val}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() )
6
1
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "BlipImageProcessor" lowerCamelCase_ = "AutoTokenizer" def __init__( self :List[Any] , __A :str , __A :Dict , __A :List[str] ) -> Any: """simple docstring""" super().__init__(__A , __A ) # add QFormer tokenizer SCREAMING_SNAKE_CASE__ = qformer_tokenizer def __call__( self :Any , __A :ImageInput = None , __A :Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __A :bool = True , __A :Union[bool, str, PaddingStrategy] = False , __A :Union[bool, str, TruncationStrategy] = None , __A :Optional[int] = None , __A :int = 0 , __A :Optional[int] = None , __A :Optional[bool] = None , __A :bool = False , __A :bool = False , __A :bool = False , __A :bool = False , __A :bool = False , __A :bool = True , __A :Optional[Union[str, TensorType]] = None , **__A :int , ) -> BatchFeature: """simple docstring""" if images is None and text is None: raise ValueError("""You have to specify at least images or text.""" ) SCREAMING_SNAKE_CASE__ = BatchFeature() if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer( text=__A , add_special_tokens=__A , padding=__A , truncation=__A , max_length=__A , stride=__A , pad_to_multiple_of=__A , return_attention_mask=__A , return_overflowing_tokens=__A , return_special_tokens_mask=__A , return_offsets_mapping=__A , return_token_type_ids=__A , return_length=__A , verbose=__A , return_tensors=__A , **__A , ) encoding.update(__A ) SCREAMING_SNAKE_CASE__ = self.qformer_tokenizer( text=__A , add_special_tokens=__A , padding=__A , truncation=__A , max_length=__A , stride=__A , pad_to_multiple_of=__A , return_attention_mask=__A , return_overflowing_tokens=__A , return_special_tokens_mask=__A , return_offsets_mapping=__A , return_token_type_ids=__A , return_length=__A , verbose=__A , return_tensors=__A , **__A , ) SCREAMING_SNAKE_CASE__ = qformer_text_encoding.pop("""input_ids""" ) SCREAMING_SNAKE_CASE__ = qformer_text_encoding.pop("""attention_mask""" ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A ) encoding.update(__A ) return encoding def _snake_case ( self :Any , *__A :List[str] , **__A :List[str] ) -> List[str]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Tuple , *__A :str , **__A :Tuple ) -> int: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _snake_case ( self :List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def _snake_case ( self :Any , __A :str , **__A :int ) -> str: """simple docstring""" if os.path.isfile(__A ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , """qformer_tokenizer""" ) self.qformer_tokenizer.save_pretrained(__A ) return super().save_pretrained(__A , **__A ) @classmethod def _snake_case ( cls :str , __A :Dict , **__A :List[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(__A , subfolder="""qformer_tokenizer""" ) SCREAMING_SNAKE_CASE__ = cls._get_arguments_from_pretrained(__A , **__A ) args.append(__A ) return cls(*__A )
6
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig _lowerCamelCase = logging.get_logger(__name__) # General docstring _lowerCamelCase = 'PoolFormerConfig' # Base docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = [1, 512, 7, 7] # Image classification docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = 'tabby, tabby cat' _lowerCamelCase = [ 'sail/poolformer_s12', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: float = 0.0 , UpperCamelCase__: bool = False ): if drop_prob == 0.0 or not training: return input SCREAMING_SNAKE_CASE__ = 1 - drop_prob SCREAMING_SNAKE_CASE__ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets SCREAMING_SNAKE_CASE__ = keep_prob + torch.rand(UpperCamelCase__ , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize SCREAMING_SNAKE_CASE__ = input.div(UpperCamelCase__ ) * random_tensor return output class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Optional[float] = None ) -> None: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = drop_prob def _snake_case ( self :Any , __A :torch.Tensor ) -> torch.Tensor: """simple docstring""" return drop_path(__A , self.drop_prob , self.training ) def _snake_case ( self :Dict ) -> str: """simple docstring""" return "p={}".format(self.drop_prob ) class UpperCamelCase_ ( nn.Module ): def __init__( self :Dict , __A :Optional[Any] , __A :Dict , __A :List[str] , __A :Optional[Any] , __A :Tuple , __A :Optional[Any]=None ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = patch_size if isinstance(__A , collections.abc.Iterable ) else (patch_size, patch_size) SCREAMING_SNAKE_CASE__ = stride if isinstance(__A , collections.abc.Iterable ) else (stride, stride) SCREAMING_SNAKE_CASE__ = padding if isinstance(__A , collections.abc.Iterable ) else (padding, padding) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , kernel_size=__A , stride=__A , padding=__A ) SCREAMING_SNAKE_CASE__ = norm_layer(__A ) if norm_layer else nn.Identity() def _snake_case ( self :Dict , __A :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.projection(__A ) SCREAMING_SNAKE_CASE__ = self.norm(__A ) return embeddings class UpperCamelCase_ ( nn.GroupNorm ): def __init__( self :Dict , __A :Tuple , **__A :Union[str, Any] ) -> Dict: """simple docstring""" super().__init__(1 , __A , **__A ) class UpperCamelCase_ ( nn.Module ): def __init__( self :List[str] , __A :Optional[int] ) -> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.AvgPoolad(__A , stride=1 , padding=pool_size // 2 , count_include_pad=__A ) def _snake_case ( self :Any , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" return self.pool(__A ) - hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Tuple , __A :Dict , __A :int , __A :Any ) -> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if isinstance(config.hidden_act , __A ): SCREAMING_SNAKE_CASE__ = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE__ = config.hidden_act def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.act_fn(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) return hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :str , __A :List[str] , __A :Tuple , __A :Dict , __A :Union[str, Any] , __A :int ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = PoolFormerPooling(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerOutput(__A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) # Useful for training neural nets SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if drop_path > 0.0 else nn.Identity() SCREAMING_SNAKE_CASE__ = config.use_layer_scale if config.use_layer_scale: SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) def _snake_case ( self :Optional[Any] , __A :Optional[int] ) -> str: """simple docstring""" if self.use_layer_scale: SCREAMING_SNAKE_CASE__ = self.pooling(self.before_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = () SCREAMING_SNAKE_CASE__ = self.output(self.after_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs else: SCREAMING_SNAKE_CASE__ = self.drop_path(self.pooling(self.before_norm(__A ) ) ) # First residual connection SCREAMING_SNAKE_CASE__ = pooling_output + hidden_states SCREAMING_SNAKE_CASE__ = () # Second residual connection inside the PoolFormerOutput block SCREAMING_SNAKE_CASE__ = self.drop_path(self.output(self.after_norm(__A ) ) ) SCREAMING_SNAKE_CASE__ = hidden_states + layer_output SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs class UpperCamelCase_ ( nn.Module ): def __init__( self :Union[str, Any] , __A :List[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = config # stochastic depth decay rule SCREAMING_SNAKE_CASE__ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings SCREAMING_SNAKE_CASE__ = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) # Transformer blocks SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers SCREAMING_SNAKE_CASE__ = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__A ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) def _snake_case ( self :str , __A :Tuple , __A :Dict=False , __A :Tuple=True ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = () if output_hidden_states else None SCREAMING_SNAKE_CASE__ = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = layers # Get patch embeddings from hidden_states SCREAMING_SNAKE_CASE__ = embedding_layer(__A ) # Send the embeddings through the blocks for _, blk in enumerate(__A ): SCREAMING_SNAKE_CASE__ = blk(__A ) SCREAMING_SNAKE_CASE__ = layer_outputs[0] if output_hidden_states: SCREAMING_SNAKE_CASE__ = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__A , hidden_states=__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PoolFormerConfig lowerCamelCase_ = "poolformer" lowerCamelCase_ = "pixel_values" lowerCamelCase_ = True def _snake_case ( self :Optional[Any] , __A :Tuple ) -> Dict: """simple docstring""" if isinstance(__A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _snake_case ( self :str , __A :Optional[Any] , __A :Union[str, Any]=False ) -> Any: """simple docstring""" if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = value _lowerCamelCase = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _lowerCamelCase = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n' @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Any ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config SCREAMING_SNAKE_CASE__ = PoolFormerEncoder(__A ) # Initialize weights and apply final processing self.post_init() def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _snake_case ( self :Dict , __A :Optional[torch.FloatTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) SCREAMING_SNAKE_CASE__ = self.encoder( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__A , hidden_states=encoder_outputs.hidden_states , ) class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :Optional[int] ) -> Tuple: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Linear(config.hidden_size , config.hidden_size ) def _snake_case ( self :List[Any] , __A :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dense(__A ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :str , __A :Union[str, Any] ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config.num_labels SCREAMING_SNAKE_CASE__ = PoolFormerModel(__A ) # Final norm SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head SCREAMING_SNAKE_CASE__ = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _snake_case ( self :int , __A :Optional[torch.FloatTensor] = None , __A :Optional[torch.LongTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ = self.poolformer( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = outputs[0] SCREAMING_SNAKE_CASE__ = self.classifier(self.norm(__A ).mean([-2, -1] ) ) SCREAMING_SNAKE_CASE__ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE__ = """single_label_classification""" else: SCREAMING_SNAKE_CASE__ = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE__ = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE__ = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE__ = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) if not return_dict: SCREAMING_SNAKE_CASE__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__A , logits=__A , hidden_states=outputs.hidden_states )
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict ): SCREAMING_SNAKE_CASE__ = set() # edges = list of graph's edges SCREAMING_SNAKE_CASE__ = get_edges(UpperCamelCase__ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = edges.pop() chosen_vertices.add(UpperCamelCase__ ) chosen_vertices.add(UpperCamelCase__ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(UpperCamelCase__ ) return chosen_vertices def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict ): SCREAMING_SNAKE_CASE__ = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
6
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device 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 ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Optional[int] , __A :Tuple=13 , __A :Dict=7 , __A :Dict=True , __A :str=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Any=False , __A :Dict=False , __A :Any=False , __A :Tuple=2 , __A :Dict=99 , __A :Optional[Any]=0 , __A :List[str]=32 , __A :Optional[int]=5 , __A :Dict=4 , __A :List[str]=0.1 , __A :Union[str, Any]=0.1 , __A :Tuple=512 , __A :Any=12 , __A :Optional[int]=2 , __A :Union[str, Any]=0.0_2 , __A :Dict=3 , __A :Optional[int]=4 , __A :Any="last" , __A :List[Any]=None , __A :Any=None , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_lengths SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = gelu_activation SCREAMING_SNAKE_CASE__ = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ = causal SCREAMING_SNAKE_CASE__ = asm SCREAMING_SNAKE_CASE__ = n_langs SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_special SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = summary_type SCREAMING_SNAKE_CASE__ = use_proj SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_input_lengths: SCREAMING_SNAKE_CASE__ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , 2 ).float() SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def _snake_case ( self :Tuple , __A :str , __A :int , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[int] , __A :Union[str, Any] , __A :Union[str, Any] , __A :str , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , lengths=__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :str , __A :Any , __A :str , __A :Union[str, Any] , __A :Optional[Any] , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[Any] , __A :Union[str, Any] , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertWithLMHeadModel(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Tuple , __A :Union[str, Any] , __A :Optional[Any] , __A :Dict , __A :Dict , __A :Union[str, Any] , __A :List[str] , __A :Optional[int] , __A :int , __A :str , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnsweringSimple(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :List[str] , __A :Any , __A :int , __A :Tuple , __A :Optional[Any] , __A :Tuple , __A :Optional[int] , __A :str , __A :int , __A :str , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnswering(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , p_mask=__A , ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _snake_case ( self :Optional[int] , __A :str , __A :Optional[int] , __A :Tuple , __A :Dict , __A :List[str] , __A :Tuple , __A :List[str] , __A :Dict , __A :List[str] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self :Optional[Any] , __A :Optional[Any] , __A :Optional[Any] , __A :List[str] , __A :Optional[Any] , __A :int , __A :Tuple , __A :Optional[int] , __A :Union[str, Any] , __A :Dict , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = FlaubertForTokenClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :str , __A :Any , __A :Tuple , __A :List[str] , __A :Tuple , __A :Any , __A :int , __A :Dict , __A :List[str] , __A :Tuple , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = FlaubertForMultipleChoice(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) lowerCamelCase_ = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _snake_case ( self :Any , __A :Optional[int] , __A :Optional[int] , __A :Dict , __A :List[Any] , __A :Tuple ) -> str: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _snake_case ( self :Tuple , __A :List[str] , __A :Optional[int] , __A :Dict=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super()._prepare_for_class(__A , __A , return_labels=__A ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) return inputs_dict def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , emb_dim=37 ) def _snake_case ( self :int ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__A ) def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__A ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__A ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__A ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__A ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__A ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @slow @require_torch_gpu def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = model_class(config=__A ) SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = torch.jit.trace( __A , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__A , os.path.join(__A , """traced_model.pt""" ) ) SCREAMING_SNAKE_CASE__ = torch.jit.load(os.path.join(__A , """traced_model.pt""" ) , map_location=__A ) loaded(inputs_dict["""input_ids"""].to(__A ) , inputs_dict["""attention_mask"""].to(__A ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [[[-2.6_2_5_1, -1.4_2_9_8, -0.0_2_2_7], [-2.8_5_1_0, -1.6_3_8_7, 0.2_2_5_8], [-2.8_1_1_4, -1.1_8_3_2, -0.3_0_6_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=1E-4 ) )
6
1
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30522, type=int) _lowerCamelCase = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: _lowerCamelCase = pickle.load(fp) logger.info('Counting occurrences for MLM.') _lowerCamelCase = Counter() for tk_ids in data: counter.update(tk_ids) _lowerCamelCase = [0] * args.vocab_size for k, v in counter.items(): _lowerCamelCase = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
6
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple=True ): model.train() SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = F.mse_loss(UpperCamelCase__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[Any]=False ): set_seed(42 ) SCREAMING_SNAKE_CASE__ = RegressionModel() SCREAMING_SNAKE_CASE__ = deepcopy(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) model.to(accelerator.device ) if sched: SCREAMING_SNAKE_CASE__ = AdamW(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = AdamW(params=ddp_model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) # Make a copy of `model` if sched: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): # Test when on a single CPU or GPU that the context manager does nothing SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): # Test on distributed setup that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int=False , UpperCamelCase__: Union[str, Any]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(UpperCamelCase__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple=False , UpperCamelCase__: List[str]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ , UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCamelCase__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n''' SCREAMING_SNAKE_CASE__ = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(UpperCamelCase__ )) if accelerator.num_processes > 1: check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=96 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if iteration < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if batch_num < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(UpperCamelCase__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(UpperCamelCase__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation(UpperCamelCase__ , UpperCamelCase__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" , """2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , """`split_batches=False`, `dispatch_batches=False`**""" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation_with_opt_and_scheduler(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
6
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'tokenizer_file': { 'bigscience/tokenizer': 'https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json', 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json', }, } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = None def __init__( self :Any , __A :List[str]=None , __A :Tuple=None , __A :Union[str, Any]=None , __A :Tuple="<unk>" , __A :Union[str, Any]="<s>" , __A :Optional[Any]="</s>" , __A :Tuple="<pad>" , __A :str=False , __A :str=False , **__A :Dict , ) -> Tuple: """simple docstring""" super().__init__( __A , __A , tokenizer_file=__A , unk_token=__A , bos_token=__A , eos_token=__A , pad_token=__A , add_prefix_space=__A , clean_up_tokenization_spaces=__A , **__A , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __A ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = getattr(__A , pre_tok_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = pre_tok_class(**__A ) SCREAMING_SNAKE_CASE__ = add_prefix_space def _snake_case ( self :Tuple , *__A :List[str] , **__A :List[Any] ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = kwargs.get("""is_split_into_words""" , __A ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._batch_encode_plus(*__A , **__A ) def _snake_case ( self :Union[str, Any] , *__A :List[str] , **__A :List[str] ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = kwargs.get("""is_split_into_words""" , __A ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._encode_plus(*__A , **__A ) def _snake_case ( self :Union[str, Any] , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A ) def _snake_case ( self :str , __A :"Conversation" ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__A , add_special_tokens=__A ) + [self.eos_token_id] ) if len(__A ) > self.model_max_length: SCREAMING_SNAKE_CASE__ = input_ids[-self.model_max_length :] return input_ids
6
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCamelCase_ = "AutoTokenizer" def __init__( self :Optional[int] , __A :Optional[Any] , __A :Dict ) -> Dict: """simple docstring""" super().__init__(__A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor def __call__( self :int , __A :str=None , __A :int=None , __A :Union[str, Any]=None , **__A :str ) -> Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :str , *__A :List[str] , **__A :List[str] ) -> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :List[str] , *__A :Any , **__A :Any ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
6
1
# Copyright 2021 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 from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowerCamelCase = 'Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = _ask_options( """In which compute environment are you running?""" , ["""This machine""", """AWS (Amazon SageMaker)"""] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: SCREAMING_SNAKE_CASE__ = get_sagemaker_input() else: SCREAMING_SNAKE_CASE__ = get_cluster_input() return config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any]=None ): if subparsers is not None: SCREAMING_SNAKE_CASE__ = subparsers.add_parser("""config""" , description=UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser("""Accelerate config command""" , description=UpperCamelCase__ ) parser.add_argument( """--config_file""" , default=UpperCamelCase__ , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , ) if subparsers is not None: parser.set_defaults(func=UpperCamelCase__ ) return parser def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = get_user_input() if args.config_file is not None: SCREAMING_SNAKE_CASE__ = args.config_file else: if not os.path.isdir(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = default_yaml_config_file if config_file.endswith(""".json""" ): config.to_json_file(UpperCamelCase__ ) else: config.to_yaml_file(UpperCamelCase__ ) print(f'''accelerate configuration saved at {config_file}''' ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = config_command_parser() SCREAMING_SNAKE_CASE__ = parser.parse_args() config_command(UpperCamelCase__ ) if __name__ == "__main__": main()
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ = True for i in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = dp[i][j - 1] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE__ = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: SCREAMING_SNAKE_CASE__ = s - 2 * j break return diff
6
1
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore _lowerCamelCase = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" _lowerCamelCase = [file for file in filepaths if file != file.lower()] if upper_files: print(F'''{len(upper_files)} files contain uppercase characters:''') print('\n'.join(upper_files) + '\n') _lowerCamelCase = [file for file in filepaths if ' ' in file] if space_files: print(F'''{len(space_files)} files contain space characters:''') print('\n'.join(space_files) + '\n') _lowerCamelCase = [file for file in filepaths if '-' in file] if hyphen_files: print(F'''{len(hyphen_files)} files contain hyphen characters:''') print('\n'.join(hyphen_files) + '\n') _lowerCamelCase = [file for file in filepaths if os.sep not in file] if nodir_files: print(F'''{len(nodir_files)} files are not in a directory:''') print('\n'.join(nodir_files) + '\n') _lowerCamelCase = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
6
1
class UpperCamelCase_ : def __init__( self :Tuple ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = {} def _snake_case ( self :Dict , __A :Tuple ) -> Tuple: """simple docstring""" if vertex not in self.adjacency: SCREAMING_SNAKE_CASE__ = {} self.num_vertices += 1 def _snake_case ( self :Optional[int] , __A :Any , __A :Optional[int] , __A :List[Any] ) -> Optional[int]: """simple docstring""" self.add_vertex(__A ) self.add_vertex(__A ) if head == tail: return SCREAMING_SNAKE_CASE__ = weight SCREAMING_SNAKE_CASE__ = weight def _snake_case ( self :int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_edges() for edge in edges: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = edge edges.remove((tail, head, weight) ) for i in range(len(__A ) ): SCREAMING_SNAKE_CASE__ = list(edges[i] ) edges.sort(key=lambda __A : e[2] ) for i in range(len(__A ) - 1 ): if edges[i][2] >= edges[i + 1][2]: SCREAMING_SNAKE_CASE__ = edges[i][2] + 1 for edge in edges: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = edge SCREAMING_SNAKE_CASE__ = weight SCREAMING_SNAKE_CASE__ = weight def __str__( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """""" for tail in self.adjacency: for head in self.adjacency[tail]: SCREAMING_SNAKE_CASE__ = self.adjacency[head][tail] string += f'''{head} -> {tail} == {weight}\n''' return string.rstrip("""\n""" ) def _snake_case ( self :Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" return self.adjacency.keys() @staticmethod def _snake_case ( __A :List[Any]=None , __A :List[Any]=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = Graph() if vertices is None: SCREAMING_SNAKE_CASE__ = [] if edges is None: SCREAMING_SNAKE_CASE__ = [] for vertex in vertices: g.add_vertex(__A ) for edge in edges: g.add_edge(*__A ) return g class UpperCamelCase_ : def __init__( self :List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} def __len__( self :Union[str, Any] ) -> List[str]: """simple docstring""" return len(self.parent ) def _snake_case ( self :Optional[int] , __A :Any ) -> Any: """simple docstring""" if item in self.parent: return self.find(__A ) SCREAMING_SNAKE_CASE__ = item SCREAMING_SNAKE_CASE__ = 0 return item def _snake_case ( self :Any , __A :Dict ) -> Optional[int]: """simple docstring""" if item not in self.parent: return self.make_set(__A ) if item != self.parent[item]: SCREAMING_SNAKE_CASE__ = self.find(self.parent[item] ) return self.parent[item] def _snake_case ( self :Optional[Any] , __A :List[Any] , __A :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.find(__A ) SCREAMING_SNAKE_CASE__ = self.find(__A ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: SCREAMING_SNAKE_CASE__ = roota return roota if self.rank[roota] < self.rank[roota]: SCREAMING_SNAKE_CASE__ = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 SCREAMING_SNAKE_CASE__ = roota return roota return None @staticmethod def _snake_case ( __A :List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = graph.num_vertices SCREAMING_SNAKE_CASE__ = Graph.UnionFind() SCREAMING_SNAKE_CASE__ = [] while num_components > 1: SCREAMING_SNAKE_CASE__ = {} for vertex in graph.get_vertices(): SCREAMING_SNAKE_CASE__ = -1 SCREAMING_SNAKE_CASE__ = graph.get_edges() for edge in edges: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = edge edges.remove((tail, head, weight) ) for edge in edges: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = edge SCREAMING_SNAKE_CASE__ = union_find.find(__A ) SCREAMING_SNAKE_CASE__ = union_find.find(__A ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: SCREAMING_SNAKE_CASE__ = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: SCREAMING_SNAKE_CASE__ = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cheap_edge[vertex] if union_find.find(__A ) != union_find.find(__A ): union_find.union(__A , __A ) mst_edges.append(cheap_edge[vertex] ) SCREAMING_SNAKE_CASE__ = num_components - 1 SCREAMING_SNAKE_CASE__ = Graph.build(edges=__A ) return mst
6
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = True def __init__( self :Optional[int] , **__A :str ) -> int: """simple docstring""" super().__init__(**__A ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE__ = kwargs.pop("""encoder""" ) SCREAMING_SNAKE_CASE__ = encoder_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""decoder""" ) SCREAMING_SNAKE_CASE__ = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = True @classmethod def _snake_case ( cls :str , __A :PretrainedConfig , __A :PretrainedConfig , **__A :List[str] ) -> PretrainedConfig: """simple docstring""" logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__A ) def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.encoder.to_dict() SCREAMING_SNAKE_CASE__ = self.decoder.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
6
1
import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 _lowerCamelCase = { 'return_dict': False, 'output_hidden_states': True, 'output_attentions': True, 'torchscript': True, 'torch_dtype': 'float16', 'use_bfloat16': True, 'tf_legacy_loss': True, 'pruned_heads': {'a': 1}, 'tie_word_embeddings': False, 'is_decoder': True, 'cross_attention_hidden_size': 128, 'add_cross_attention': True, 'tie_encoder_decoder': True, 'max_length': 50, 'min_length': 3, 'do_sample': True, 'early_stopping': True, 'num_beams': 3, 'num_beam_groups': 3, 'diversity_penalty': 0.5, 'temperature': 2.0, 'top_k': 10, 'top_p': 0.7, 'typical_p': 0.2, 'repetition_penalty': 0.8, 'length_penalty': 0.8, 'no_repeat_ngram_size': 5, 'encoder_no_repeat_ngram_size': 5, 'bad_words_ids': [1, 2, 3], 'num_return_sequences': 3, 'chunk_size_feed_forward': 5, 'output_scores': True, 'return_dict_in_generate': True, 'forced_bos_token_id': 2, 'forced_eos_token_id': 3, 'remove_invalid_values': True, 'architectures': ['BertModel'], 'finetuning_task': 'translation', 'id2label': {0: 'label'}, 'label2id': {'label': '0'}, 'tokenizer_class': 'BertTokenizerFast', 'prefix': 'prefix', 'bos_token_id': 6, 'pad_token_id': 7, 'eos_token_id': 8, 'sep_token_id': 9, 'decoder_start_token_id': 10, 'exponential_decay_length_penalty': (5, 1.01), 'suppress_tokens': [0, 1], 'begin_suppress_tokens': 2, 'task_specific_params': {'translation': 'some_params'}, 'problem_type': 'regression', } @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): @classmethod def _snake_case ( cls :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TOKEN HfFolder.save_token(__A ) @classmethod def _snake_case ( cls :Union[str, Any] ) -> Optional[int]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="""test-config""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-config-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-config""" ) except HTTPError: pass def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("""test-config""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__A , getattr(__A , __A ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-config""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__A , repo_id="""test-config""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__A , getattr(__A , __A ) ) def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("""valid_org/test-config-org""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""valid_org/test-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__A , getattr(__A , __A ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-config-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( __A , repo_id="""valid_org/test-config-org""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""valid_org/test-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__A , getattr(__A , __A ) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" CustomConfig.register_for_auto_class() SCREAMING_SNAKE_CASE__ = CustomConfig(attribute=42 ) config.push_to_hub("""test-dynamic-config""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"""AutoConfig""": """custom_configuration.CustomConfig"""} ) SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained(f'''{USER}/test-dynamic-config''' , trust_remote_code=__A ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , """CustomConfig""" ) self.assertEqual(new_config.attribute , 42 ) class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated SCREAMING_SNAKE_CASE__ = c.n_embd + 1 # int SCREAMING_SNAKE_CASE__ = c.resid_pdrop + 1.0 # float SCREAMING_SNAKE_CASE__ = not c.scale_attn_weights # bool SCREAMING_SNAKE_CASE__ = c.summary_type + """foo""" # str c.update_from_string( f'''n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}''' ) self.assertEqual(__A , c.n_embd , """mismatch for key: n_embd""" ) self.assertEqual(__A , c.resid_pdrop , """mismatch for key: resid_pdrop""" ) self.assertEqual(__A , c.scale_attn_weights , """mismatch for key: scale_attn_weights""" ) self.assertEqual(__A , c.summary_type , """mismatch for key: summary_type""" ) def _snake_case ( self :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = PretrainedConfig() SCREAMING_SNAKE_CASE__ = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( __A , ["""is_encoder_decoder""", """_name_or_path""", """_commit_hash""", """transformers_version"""] ) SCREAMING_SNAKE_CASE__ = [key for key, value in config_common_kwargs.items() if value == getattr(__A , __A )] if len(__A ) > 0: raise ValueError( """The following keys are set with the default values in""" """ `test_configuration_common.config_common_kwargs` pick another value for them:""" f''' {', '.join(__A )}.''' ) def _snake_case ( self :Optional[int] ) -> Optional[int]: """simple docstring""" with self.assertRaises(__A ): # config is in subfolder, the following should not work without specifying the subfolder SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert-subfolder""" ) SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert-subfolder""" , subfolder="""bert""" ) self.assertIsNotNone(__A ) def _snake_case ( self :str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = mock.Mock() SCREAMING_SNAKE_CASE__ = 500 SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = HTTPError SCREAMING_SNAKE_CASE__ = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=__A ) as mock_head: SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json""" ) def _snake_case ( self :Tuple ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained("""bert-base-cased""" ) SCREAMING_SNAKE_CASE__ = ["""config.4.0.0.json"""] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = 2 json.dump(configuration.to_dict() , open(os.path.join(__A , """config.4.0.0.json""" ) , """w""" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained(__A ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 SCREAMING_SNAKE_CASE__ = ["""config.42.0.0.json"""] SCREAMING_SNAKE_CASE__ = 768 configuration.save_pretrained(__A ) shutil.move(os.path.join(__A , """config.4.0.0.json""" ) , os.path.join(__A , """config.42.0.0.json""" ) ) SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained(__A ) self.assertEqual(new_configuration.hidden_size , 768 ) def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = """hf-internal-testing/test-two-configs""" import transformers as new_transformers SCREAMING_SNAKE_CASE__ = """v4.0.0""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = new_transformers.models.auto.AutoConfig.from_pretrained( __A , return_unused_kwargs=__A ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(__A , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers SCREAMING_SNAKE_CASE__ = """v3.0.0""" SCREAMING_SNAKE_CASE__ = old_transformers.models.auto.AutoConfig.from_pretrained(__A ) self.assertEqual(old_configuration.hidden_size , 768 )
6
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowerCamelCase_ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"text": Value("string" )} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "text" lowerCamelCase_ = "labels" def _snake_case ( self :Any , __A :Dict ) -> Optional[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] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :str ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
6
1
from typing import Dict, Optional import numpy as np import datasets _lowerCamelCase = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' _lowerCamelCase = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' _lowerCamelCase = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: bool , UpperCamelCase__: Optional[Dict[int, int]] = None , UpperCamelCase__: bool = False , ): if label_map is not None: for old_id, new_id in label_map.items(): SCREAMING_SNAKE_CASE__ = new_id # turn into Numpy arrays SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ) if reduce_labels: SCREAMING_SNAKE_CASE__ = 255 SCREAMING_SNAKE_CASE__ = label - 1 SCREAMING_SNAKE_CASE__ = 255 SCREAMING_SNAKE_CASE__ = label != ignore_index SCREAMING_SNAKE_CASE__ = np.not_equal(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pred_label[mask] SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ )[mask] SCREAMING_SNAKE_CASE__ = pred_label[pred_label == label] SCREAMING_SNAKE_CASE__ = np.histogram(UpperCamelCase__ , bins=UpperCamelCase__ , range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE__ = np.histogram(UpperCamelCase__ , bins=UpperCamelCase__ , range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE__ = np.histogram(UpperCamelCase__ , bins=UpperCamelCase__ , range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE__ = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: bool , UpperCamelCase__: Optional[Dict[int, int]] = None , UpperCamelCase__: bool = False , ): SCREAMING_SNAKE_CASE__ = np.zeros((num_labels,) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = np.zeros((num_labels,) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = np.zeros((num_labels,) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = intersect_and_union( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int , UpperCamelCase__: bool , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: Optional[Dict[int, int]] = None , UpperCamelCase__: bool = False , ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = total_intersect_and_union( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # compute metrics SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = total_area_intersect.sum() / total_area_label.sum() SCREAMING_SNAKE_CASE__ = total_area_intersect / total_area_union SCREAMING_SNAKE_CASE__ = total_area_intersect / total_area_label SCREAMING_SNAKE_CASE__ = np.nanmean(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.nanmean(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = all_acc SCREAMING_SNAKE_CASE__ = iou SCREAMING_SNAKE_CASE__ = acc if nan_to_num is not None: SCREAMING_SNAKE_CASE__ = {metric: np.nan_to_num(UpperCamelCase__ , nan=UpperCamelCase__ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { """predictions""": datasets.Sequence(datasets.Sequence(datasets.Value("""uint16""" ) ) ), """references""": datasets.Sequence(datasets.Sequence(datasets.Value("""uint16""" ) ) ), } ) , reference_urls=[ """https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py""" ] , ) def _snake_case ( self :Dict , __A :Any , __A :Dict , __A :int , __A :bool , __A :Optional[int] = None , __A :Optional[Dict[int, int]] = None , __A :bool = False , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = mean_iou( results=__A , gt_seg_maps=__A , num_labels=__A , ignore_index=__A , nan_to_num=__A , label_map=__A , reduce_labels=__A , ) return iou_result
6
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = model.config SCREAMING_SNAKE_CASE__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) SCREAMING_SNAKE_CASE__ = MBartConfig( is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , ) return encoder_config, decoder_config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if "encoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" ) if "decoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if name.startswith("""encoder""" ): if "layers" in name: SCREAMING_SNAKE_CASE__ = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "mask" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight""" if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias""" return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_split[3] ) SCREAMING_SNAKE_CASE__ = int(key_split[5] ) SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE__ = val[:dim, :] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ = val[-dim:, :] else: SCREAMING_SNAKE_CASE__ = val[:dim] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: SCREAMING_SNAKE_CASE__ = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): # load original model SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval() # load HuggingFace model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = original_model.state_dict() SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify results on scanned document SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" ) SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" SCREAMING_SNAKE_CASE__ = """When is the coffee break?""" SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>""" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: SCREAMING_SNAKE_CASE__ = """<s_cord>""" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": SCREAMING_SNAKE_CASE__ = """s_cord-v2>""" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>""" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt SCREAMING_SNAKE_CASE__ = """hello world""" else: raise ValueError("""Model name not supported""" ) SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[ """input_ids""" ] SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) # verify encoder hidden states SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) # verify decoder hidden states SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, 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 and processor to the 🤗 hub.', ) _lowerCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
6
1
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser _lowerCamelCase = logging.getLogger(__name__) torch.set_grad_enabled(False) _lowerCamelCase = 'cuda' if torch.cuda.is_available() else 'cpu' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[Any]=100 , UpperCamelCase__: Tuple=" " ): SCREAMING_SNAKE_CASE__ = text.split(UpperCamelCase__ ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(UpperCamelCase__ ) , UpperCamelCase__ )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = [], [] for title, text in zip(documents["""title"""] , documents["""text"""] ): if text is not None: for passage in split_text(UpperCamelCase__ ): titles.append(title if title is not None else """""" ) texts.append(UpperCamelCase__ ) return {"title": titles, "text": texts} def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict , UpperCamelCase__: DPRContextEncoder , UpperCamelCase__: DPRContextEncoderTokenizerFast ): SCREAMING_SNAKE_CASE__ = ctx_tokenizer( documents["""title"""] , documents["""text"""] , truncation=UpperCamelCase__ , padding="""longest""" , return_tensors="""pt""" )["""input_ids"""] SCREAMING_SNAKE_CASE__ = ctx_encoder(input_ids.to(device=UpperCamelCase__ ) , return_dict=UpperCamelCase__ ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: "RagExampleArguments" , UpperCamelCase__: "ProcessingArguments" , UpperCamelCase__: "IndexHnswArguments" , ): ###################################### logger.info("""Step 1 - Create the dataset""" ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way SCREAMING_SNAKE_CASE__ = load_dataset( """csv""" , data_files=[rag_example_args.csv_path] , split="""train""" , delimiter="""\t""" , column_names=["""title""", """text"""] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=processing_args.num_proc ) # And compute the embeddings SCREAMING_SNAKE_CASE__ = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) SCREAMING_SNAKE_CASE__ = Features( {"""text""": Value("""string""" ), """title""": Value("""string""" ), """embeddings""": Sequence(Value("""float32""" ) )} ) # optional, save as float32 instead of float64 to save space SCREAMING_SNAKE_CASE__ = dataset.map( partial(UpperCamelCase__ , ctx_encoder=UpperCamelCase__ , ctx_tokenizer=UpperCamelCase__ ) , batched=UpperCamelCase__ , batch_size=processing_args.batch_size , features=UpperCamelCase__ , ) # And finally save your dataset SCREAMING_SNAKE_CASE__ = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset""" ) dataset.save_to_disk(UpperCamelCase__ ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info("""Step 2 - Index the dataset""" ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search SCREAMING_SNAKE_CASE__ = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index("""embeddings""" , custom_index=UpperCamelCase__ ) # And save the index SCREAMING_SNAKE_CASE__ = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset_hnsw_index.faiss""" ) dataset.get_index("""embeddings""" ).save(UpperCamelCase__ ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class UpperCamelCase_ : lowerCamelCase_ = field( default=str(Path(UpperCamelCase__ ).parent / "test_run" / "dummy-kb" / "my_knowledge_dataset.csv" ) , metadata={"help": "Path to a tab-separated csv file with columns 'title' and 'text'"} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."} , ) lowerCamelCase_ = field( default="facebook/rag-sequence-nq" , metadata={"help": "The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"} , ) lowerCamelCase_ = field( default="facebook/dpr-ctx_encoder-multiset-base" , metadata={ "help": ( "The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or" " 'facebook/dpr-ctx_encoder-multiset-base'" ) } , ) lowerCamelCase_ = field( default=str(Path(UpperCamelCase__ ).parent / "test_run" / "dummy-kb" ) , metadata={"help": "Path to a directory where the dataset passages and the index will be saved"} , ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={ "help": "The number of processes to use to split the documents into passages. Default is single process." } , ) lowerCamelCase_ = field( default=16 , metadata={ "help": "The batch size to use when computing the passages embeddings using the DPR context encoder." } , ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field( default=7_68 , metadata={"help": "The dimension of the embeddings to pass to the HNSW Faiss index."} , ) lowerCamelCase_ = field( default=1_28 , metadata={ "help": ( "The number of bi-directional links created for every new element during the HNSW index construction." ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) _lowerCamelCase = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: _lowerCamelCase = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
6
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_dpmpp_2m""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=7.5 , num_inference_steps=15 , output_type="""np""" , use_karras_sigmas=__A , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
6
1
from scipy.stats import pearsonr import datasets _lowerCamelCase = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' _lowerCamelCase = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' _lowerCamelCase = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""] , ) def _snake_case ( self :Union[str, Any] , __A :List[Any] , __A :Optional[Any] , __A :int=False ) -> int: """simple docstring""" if return_pvalue: SCREAMING_SNAKE_CASE__ = pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE__ = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE__ = n return int(UpperCamelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
6
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "dpr" def __init__( self :Optional[Any] , __A :List[str]=3_0522 , __A :List[str]=768 , __A :int=12 , __A :Union[str, Any]=12 , __A :str=3072 , __A :Optional[int]="gelu" , __A :Optional[Any]=0.1 , __A :Union[str, Any]=0.1 , __A :Optional[Any]=512 , __A :Any=2 , __A :Optional[Any]=0.0_2 , __A :int=1E-12 , __A :Optional[Any]=0 , __A :Optional[Any]="absolute" , __A :int = 0 , **__A :str , ) -> Optional[int]: """simple docstring""" super().__init__(pad_token_id=__A , **__A ) SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = projection_dim SCREAMING_SNAKE_CASE__ = position_embedding_type
6
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) )
6
1
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 UpperCamelCase_ : def __init__( self :Optional[Any] , __A :List[Any] , __A :int=13 , __A :Tuple=3 , __A :Any=True , __A :Any=True , __A :Optional[Any]=0.1 , __A :List[Any]=0.1 , __A :Dict=224 , __A :Optional[Any]=1000 , __A :List[Any]=[3, 3, 6, 4] , __A :List[Any]=[48, 56, 112, 220] , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = layer_depths SCREAMING_SNAKE_CASE__ = embed_dims def _snake_case ( self :Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, pixel_values, labels def _snake_case ( self :Union[str, Any] ) -> int: """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=__A , layer_scale_init_value=1E-5 , ) def _snake_case ( self :Tuple , __A :Dict , __A :str , __A :List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = SwiftFormerModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def _snake_case ( self :Tuple , __A :str , __A :List[str] , __A :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = SwiftFormerForImageClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE__ = SwiftFormerForImageClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :int ) -> str: """simple docstring""" ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () lowerCamelCase_ = ( {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester( self , config_class=__A , has_text_modality=__A , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def _snake_case ( self :Dict ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def _snake_case ( self :Tuple ) -> Union[str, Any]: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__A , nn.Linear ) ) def _snake_case ( self :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def _snake_case ( self :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @slow def _snake_case ( self :Dict ) -> str: """simple docstring""" for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = SwiftFormerModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" pass def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" def check_hidden_states_output(__A :List[Any] , __A :str , __A :List[str] ): SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.hidden_states SCREAMING_SNAKE_CASE__ = 8 self.assertEqual(len(__A ) , __A ) # 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(__A ) ): 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), ] ) , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" def _config_zero_init(__A :Optional[int] ): SCREAMING_SNAKE_CASE__ = copy.deepcopy(__A ) 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(__A , __A , 1E-10 ) if isinstance(getattr(__A , __A , __A ) , __A ): SCREAMING_SNAKE_CASE__ = _config_zero_init(getattr(__A , __A ) ) setattr(__A , __A , __A ) return configs_no_init SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = _config_zero_init(__A ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(config=__A ) 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 _snake_case ( self :str ) -> str: """simple docstring""" pass def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class UpperCamelCase_ ( unittest.TestCase ): @cached_property def _snake_case ( self :Optional[int] ) -> List[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(__A ) SCREAMING_SNAKE_CASE__ = self.default_image_processor SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ).to(__A ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**__A ) # verify the logits SCREAMING_SNAKE_CASE__ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) )
6
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""": """Friday""", """6""": """Saturday""", } SCREAMING_SNAKE_CASE__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(UpperCamelCase__ ) < 11: raise ValueError("""Must be 10 characters long""" ) # Get month SCREAMING_SNAKE_CASE__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("""Month must be between 1 - 12""" ) SCREAMING_SNAKE_CASE__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get day SCREAMING_SNAKE_CASE__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("""Date must be between 1 - 31""" ) # Get second separator SCREAMING_SNAKE_CASE__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get year SCREAMING_SNAKE_CASE__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8_500: raise ValueError( """Year out of range. There has to be some sort of limit...right?""" ) # Get datetime obj for validation SCREAMING_SNAKE_CASE__ = datetime.date(int(UpperCamelCase__ ) , int(UpperCamelCase__ ) , int(UpperCamelCase__ ) ) # Start math if m <= 2: SCREAMING_SNAKE_CASE__ = y - 1 SCREAMING_SNAKE_CASE__ = m + 12 # maths var SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[:2] ) SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[2:] ) SCREAMING_SNAKE_CASE__ = int(2.6 * m - 5.3_9 ) SCREAMING_SNAKE_CASE__ = int(c / 4 ) SCREAMING_SNAKE_CASE__ = int(k / 4 ) SCREAMING_SNAKE_CASE__ = int(d + k ) SCREAMING_SNAKE_CASE__ = int(t + u + v + x ) SCREAMING_SNAKE_CASE__ = int(z - (2 * c) ) SCREAMING_SNAKE_CASE__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" ) # Response SCREAMING_SNAKE_CASE__ = f'''Your date {date_input}, is a {days[str(UpperCamelCase__ )]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) _lowerCamelCase = parser.parse_args() zeller(args.date_input)
6
1
import sys import turtle def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: tuple[float, float] , UpperCamelCase__: tuple[float, float] ): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: tuple[float, float] , UpperCamelCase__: tuple[float, float] , UpperCamelCase__: tuple[float, float] , UpperCamelCase__: int , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(UpperCamelCase__ , get_mid(UpperCamelCase__ , UpperCamelCase__ ) , get_mid(UpperCamelCase__ , UpperCamelCase__ ) , depth - 1 ) triangle(UpperCamelCase__ , get_mid(UpperCamelCase__ , UpperCamelCase__ ) , get_mid(UpperCamelCase__ , UpperCamelCase__ ) , depth - 1 ) triangle(UpperCamelCase__ , get_mid(UpperCamelCase__ , UpperCamelCase__ ) , get_mid(UpperCamelCase__ , UpperCamelCase__ ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( 'Correct format for using this script: ' 'python fractals.py <int:depth_for_fractal>' ) _lowerCamelCase = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor('red') _lowerCamelCase = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
6
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30522, type=int) _lowerCamelCase = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: _lowerCamelCase = pickle.load(fp) logger.info('Counting occurrences for MLM.') _lowerCamelCase = Counter() for tk_ids in data: counter.update(tk_ids) _lowerCamelCase = [0] * args.vocab_size for k, v in counter.items(): _lowerCamelCase = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
6
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """ZinengTang/tvlt-base""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() def _snake_case ( self :Optional[int] , **__A :List[str] ) -> Union[str, Any]: """simple docstring""" return TvltImageProcessor.from_pretrained(self.checkpoint , **__A ) def _snake_case ( self :Dict , **__A :Union[str, Any] ) -> str: """simple docstring""" return TvltFeatureExtractor.from_pretrained(self.checkpoint , **__A ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ = TvltProcessor(image_processor=__A , feature_extractor=__A ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , __A ) self.assertIsInstance(processor.image_processor , __A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ = TvltProcessor(image_processor=__A , feature_extractor=__A ) SCREAMING_SNAKE_CASE__ = np.ones([1_2000] ) SCREAMING_SNAKE_CASE__ = feature_extractor(__A , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ = processor(audio=__A , return_tensors="""np""" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _snake_case ( self :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ = TvltProcessor(image_processor=__A , feature_extractor=__A ) SCREAMING_SNAKE_CASE__ = np.ones([3, 224, 224] ) SCREAMING_SNAKE_CASE__ = image_processor(__A , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ = processor(images=__A , return_tensors="""np""" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _snake_case ( self :Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ = TvltProcessor(image_processor=__A , feature_extractor=__A ) SCREAMING_SNAKE_CASE__ = np.ones([1_2000] ) SCREAMING_SNAKE_CASE__ = np.ones([3, 224, 224] ) SCREAMING_SNAKE_CASE__ = processor(audio=__A , images=__A ) self.assertListEqual(list(inputs.keys() ) , ["""audio_values""", """audio_mask""", """pixel_values""", """pixel_mask"""] ) # test if it raises when no input is passed with pytest.raises(__A ): processor() def _snake_case ( self :Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_feature_extractor() SCREAMING_SNAKE_CASE__ = TvltProcessor(image_processor=__A , feature_extractor=__A ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="""`processor` and `image_processor`+`feature_extractor` model input names do not match""" , )
6
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
1
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Any , __A :Any , __A :Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = np.array(__A ) SCREAMING_SNAKE_CASE__ = np.array([len(__A ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self :Dict , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" return (self.token_ids[index], self.lengths[index]) def __len__( self :str ) -> List[Any]: """simple docstring""" return len(self.lengths ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.params.max_model_input_size SCREAMING_SNAKE_CASE__ = self.lengths > max_len logger.info(f'''Splitting {sum(__A )} too long sequences.''' ) def divide_chunks(__A :Dict , __A :Optional[Any] ): return [l[i : i + n] for i in range(0 , len(__A ) , __A )] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] if self.params.mlm: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""] else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: SCREAMING_SNAKE_CASE__ = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: SCREAMING_SNAKE_CASE__ = np.insert(__A , 0 , __A ) if sub_s[-1] != sep_id: SCREAMING_SNAKE_CASE__ = np.insert(__A , len(__A ) , __A ) assert len(__A ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(__A ) new_tok_ids.extend(__A ) new_lengths.extend([len(__A ) for l in sub_seqs] ) SCREAMING_SNAKE_CASE__ = np.array(__A ) SCREAMING_SNAKE_CASE__ = np.array(__A ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = len(self ) SCREAMING_SNAKE_CASE__ = self.lengths > 11 SCREAMING_SNAKE_CASE__ = self.token_ids[indices] SCREAMING_SNAKE_CASE__ = self.lengths[indices] SCREAMING_SNAKE_CASE__ = len(self ) logger.info(f'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def _snake_case ( self :str ) -> Any: """simple docstring""" if "unk_token" not in self.params.special_tok_ids: return else: SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""unk_token"""] SCREAMING_SNAKE_CASE__ = len(self ) SCREAMING_SNAKE_CASE__ = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) SCREAMING_SNAKE_CASE__ = (unk_occs / self.lengths) < 0.5 SCREAMING_SNAKE_CASE__ = self.token_ids[indices] SCREAMING_SNAKE_CASE__ = self.lengths[indices] SCREAMING_SNAKE_CASE__ = len(self ) logger.info(f'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" if not self.params.is_master: return logger.info(f'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def _snake_case ( self :List[Any] , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [t[0] for t in batch] SCREAMING_SNAKE_CASE__ = [t[1] for t in batch] assert len(__A ) == len(__A ) # Max for paddings SCREAMING_SNAKE_CASE__ = max(__A ) # Pad token ids if self.params.mlm: SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""pad_token"""] else: SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""unk_token"""] SCREAMING_SNAKE_CASE__ = [list(t.astype(__A ) ) + [pad_idx] * (max_seq_len_ - len(__A )) for t in token_ids] assert len(tk_ ) == len(__A ) assert all(len(__A ) == max_seq_len_ for t in tk_ ) SCREAMING_SNAKE_CASE__ = torch.tensor(tk_ ) # (bs, max_seq_len_) SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) # (bs) return tk_t, lg_t
6
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "OwlViTImageProcessor" lowerCamelCase_ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self :Optional[Any] , __A :int=None , __A :Optional[int]=None , **__A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :str , __A :Dict=None , __A :List[str]=None , __A :str=None , __A :Optional[int]="max_length" , __A :Tuple="np" , **__A :int ) -> Tuple: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(__A , __A ) or (isinstance(__A , __A ) and not isinstance(text[0] , __A )): SCREAMING_SNAKE_CASE__ = [self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )] elif isinstance(__A , __A ) and isinstance(text[0] , __A ): SCREAMING_SNAKE_CASE__ = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ = max([len(__A ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(__A ) != max_num_queries: SCREAMING_SNAKE_CASE__ = t + [""" """] * (max_num_queries - len(__A )) SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , padding=__A , return_tensors=__A , **__A ) encodings.append(__A ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = input_ids SCREAMING_SNAKE_CASE__ = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = self.image_processor( __A , return_tensors=__A , **__A ).pixel_values SCREAMING_SNAKE_CASE__ = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Dict , **__A :Dict ) -> Optional[int]: """simple docstring""" return self.image_processor.post_process(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Dict , **__A :List[str] ) -> Optional[Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*__A , **__A ) def _snake_case ( self :str , *__A :List[str] , **__A :Union[str, Any] ) -> Any: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*__A , **__A ) def _snake_case ( self :Dict , *__A :List[str] , **__A :List[str] ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Dict , *__A :Dict , **__A :List[str] ) -> str: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class @property def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __A , ) return self.image_processor
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = 0 while b > 0: if b & 1: SCREAMING_SNAKE_CASE__ = ((res % c) + (a % c)) % c a += a b >>= 1 return res
6
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self :Union[str, Any] , __A :int = 3 , __A :int = 3 , __A :Tuple[str] = ("DownEncoderBlock2D",) , __A :Tuple[str] = ("UpDecoderBlock2D",) , __A :Tuple[int] = (64,) , __A :int = 1 , __A :str = "silu" , __A :int = 3 , __A :int = 32 , __A :int = 256 , __A :int = 32 , __A :Optional[int] = None , __A :float = 0.1_8_2_1_5 , __A :str = "group" , ) -> Any: """simple docstring""" super().__init__() # pass init params to Encoder SCREAMING_SNAKE_CASE__ = Encoder( in_channels=__A , out_channels=__A , down_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , double_z=__A , ) SCREAMING_SNAKE_CASE__ = vq_embed_dim if vq_embed_dim is not None else latent_channels SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = VectorQuantizer(__A , __A , beta=0.2_5 , remap=__A , sane_index_shape=__A ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) # pass init params to Decoder SCREAMING_SNAKE_CASE__ = Decoder( in_channels=__A , out_channels=__A , up_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , norm_type=__A , ) @apply_forward_hook def _snake_case ( self :Union[str, Any] , __A :torch.FloatTensor , __A :bool = True ) -> VQEncoderOutput: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.encoder(__A ) SCREAMING_SNAKE_CASE__ = self.quant_conv(__A ) if not return_dict: return (h,) return VQEncoderOutput(latents=__A ) @apply_forward_hook def _snake_case ( self :Tuple , __A :torch.FloatTensor , __A :bool = False , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" if not force_not_quantize: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = h SCREAMING_SNAKE_CASE__ = self.post_quant_conv(__A ) SCREAMING_SNAKE_CASE__ = self.decoder(__A , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=__A ) def _snake_case ( self :int , __A :torch.FloatTensor , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample SCREAMING_SNAKE_CASE__ = self.encode(__A ).latents SCREAMING_SNAKE_CASE__ = self.decode(__A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__A )
6
1
import requests from bsa import BeautifulSoup def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str = "https://www.worldometers.info/coronavirus" ): SCREAMING_SNAKE_CASE__ = BeautifulSoup(requests.get(UpperCamelCase__ ).text , """html.parser""" ) SCREAMING_SNAKE_CASE__ = soup.findAll("""h1""" ) SCREAMING_SNAKE_CASE__ = soup.findAll("""div""" , {"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" , {"""class""": """panel-title"""} ) values += soup.findAll("""div""" , {"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(UpperCamelCase__ , UpperCamelCase__ )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
6
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = jnp.floataa lowerCamelCase_ = True def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = nn.Dense(5 , dtype=self.dtype ) def __call__( self :List[Any] , *__A :int , **__A :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super().__call__(*__A , **__A ) SCREAMING_SNAKE_CASE__ = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = FlaxBigBirdForNaturalQuestionsModule def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): def cross_entropy(UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=None ): SCREAMING_SNAKE_CASE__ = logits.shape[-1] SCREAMING_SNAKE_CASE__ = (labels[..., None] == jnp.arange(UpperCamelCase__ )[None]).astype("""f4""" ) SCREAMING_SNAKE_CASE__ = jax.nn.log_softmax(UpperCamelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE__ = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: SCREAMING_SNAKE_CASE__ = reduction(UpperCamelCase__ ) return loss SCREAMING_SNAKE_CASE__ = partial(UpperCamelCase__ , reduction=jnp.mean ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class UpperCamelCase_ : lowerCamelCase_ = "google/bigbird-roberta-base" lowerCamelCase_ = 30_00 lowerCamelCase_ = 1_05_00 lowerCamelCase_ = 1_28 lowerCamelCase_ = 3 lowerCamelCase_ = 1 lowerCamelCase_ = 5 # tx_args lowerCamelCase_ = 3e-5 lowerCamelCase_ = 0.0 lowerCamelCase_ = 2_00_00 lowerCamelCase_ = 0.0095 lowerCamelCase_ = "bigbird-roberta-natural-questions" lowerCamelCase_ = "training-expt" lowerCamelCase_ = "data/nq-training.jsonl" lowerCamelCase_ = "data/nq-validation.jsonl" def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(self.base_dir , self.save_dir ) SCREAMING_SNAKE_CASE__ = self.batch_size_per_device * jax.device_count() @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 40_96 # no dynamic padding on TPUs def __call__( self :Optional[Any] , __A :Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.collate_fn(__A ) SCREAMING_SNAKE_CASE__ = jax.tree_util.tree_map(__A , __A ) return batch def _snake_case ( self :List[Any] , __A :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.fetch_inputs(features["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = { """input_ids""": jnp.array(__A , dtype=jnp.intaa ), """attention_mask""": jnp.array(__A , dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ), } return batch def _snake_case ( self :Tuple , __A :list ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self._fetch_inputs(__A ) for ids in input_ids] return zip(*__A ) def _snake_case ( self :List[str] , __A :list ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [1 for _ in range(len(__A ) )] while len(__A ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=None ): if seed is not None: SCREAMING_SNAKE_CASE__ = dataset.shuffle(seed=UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) // batch_size ): SCREAMING_SNAKE_CASE__ = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase__ ) @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] , **UpperCamelCase__: Optional[int] ): def loss_fn(UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=UpperCamelCase__ , dropout_rng=UpperCamelCase__ , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs return state.loss_fn( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = jax.random.split(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.value_and_grad(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = grad_fn(state.params ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean(UpperCamelCase__ , """batch""" ) SCREAMING_SNAKE_CASE__ = state.apply_gradients(grads=UpperCamelCase__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , **UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=state.params , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs SCREAMING_SNAKE_CASE__ = state.loss_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class UpperCamelCase_ ( train_state.TrainState ): lowerCamelCase_ = struct.field(pytree_node=UpperCamelCase__ ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None def _snake_case ( self :List[Any] , __A :str , __A :str , __A :str , __A :Tuple=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = model.params SCREAMING_SNAKE_CASE__ = TrainState.create( apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , ) if ckpt_dir is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = restore_checkpoint(__A , __A ) SCREAMING_SNAKE_CASE__ = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = build_tx(**__A ) SCREAMING_SNAKE_CASE__ = train_state.TrainState( step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = data_collator SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = jax_utils.replicate(__A ) return state def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :int , __A :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.args SCREAMING_SNAKE_CASE__ = len(__A ) // args.batch_size SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ = jax.random.split(__A , jax.device_count() ) for epoch in range(args.max_epochs ): SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , args.batch_size , seed=__A ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc=f'''Running EPOCH-{epoch}''' ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.train_step_fn(__A , __A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(state.step ) SCREAMING_SNAKE_CASE__ = running_loss.item() / i SCREAMING_SNAKE_CASE__ = self.scheduler_fn(state_step - 1 ) SCREAMING_SNAKE_CASE__ = self.evaluate(__A , __A ) SCREAMING_SNAKE_CASE__ = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(__A ) ) self.logger.log(__A , commit=__A ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__A ) def _snake_case ( self :List[str] , __A :Dict , __A :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , self.args.batch_size ) SCREAMING_SNAKE_CASE__ = len(__A ) // self.args.batch_size SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc="""Evaluating ... """ ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ = self.val_step_fn(__A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _snake_case ( self :List[Any] , __A :Any , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(__A ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=""" ... """ ) self.model_save_fn(__A , params=state.params ) with open(os.path.join(__A , """opt_state.msgpack""" ) , """wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__A , """args.joblib""" ) ) joblib.dump(self.data_collator , os.path.join(__A , """data_collator.joblib""" ) ) with open(os.path.join(__A , """training_state.json""" ) , """w""" ) as f: json.dump({"""step""": state.step.item()} , __A ) print("""DONE""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=""" ... """ ) with open(os.path.join(UpperCamelCase__ , """flax_model.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase__ , """opt_state.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.opt_state , f.read() ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """args.joblib""" ) ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """data_collator.joblib""" ) ) with open(os.path.join(UpperCamelCase__ , """training_state.json""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = num_train_steps - warmup_steps SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=UpperCamelCase__ , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=1e-7 , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): def weight_decay_mask(UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = traverse_util.flatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = scheduler_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.adamw(learning_rate=UpperCamelCase__ , weight_decay=UpperCamelCase__ , mask=UpperCamelCase__ ) return tx, lr
6
1
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ = SamImageProcessor() SCREAMING_SNAKE_CASE__ = SamProcessor(__A ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self :Dict , **__A :Any ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__A ).image_processor def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ = [Image.fromarray(np.moveaxis(__A , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = self.get_image_processor(do_normalize=__A , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=__A , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __A ) def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=__A ) SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = image_processor(__A , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ = processor(images=__A , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _snake_case ( self :Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=__A ) SCREAMING_SNAKE_CASE__ = [torch.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ = [[1764, 2646]] SCREAMING_SNAKE_CASE__ = [[683, 1024]] SCREAMING_SNAKE_CASE__ = processor.post_process_masks(__A , __A , __A ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) SCREAMING_SNAKE_CASE__ = processor.post_process_masks( __A , torch.tensor(__A ) , torch.tensor(__A ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np SCREAMING_SNAKE_CASE__ = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ = processor.post_process_masks(__A , np.array(__A ) , np.array(__A ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) SCREAMING_SNAKE_CASE__ = [[1, 0], [0, 1]] with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = processor.post_process_masks(__A , np.array(__A ) , np.array(__A ) ) @require_vision @require_tf class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ = SamImageProcessor() SCREAMING_SNAKE_CASE__ = SamProcessor(__A ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self :Any , **__A :Union[str, Any] ) -> str: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__A ).image_processor def _snake_case ( self :str ) -> List[str]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self :int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ = [Image.fromarray(np.moveaxis(__A , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self :int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = self.get_image_processor(do_normalize=__A , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=__A , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __A ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=__A ) SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = image_processor(__A , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ = processor(images=__A , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _snake_case ( self :Dict ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=__A ) SCREAMING_SNAKE_CASE__ = [tf.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ = [[1764, 2646]] SCREAMING_SNAKE_CASE__ = [[683, 1024]] SCREAMING_SNAKE_CASE__ = processor.post_process_masks(__A , __A , __A , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) SCREAMING_SNAKE_CASE__ = processor.post_process_masks( __A , tf.convert_to_tensor(__A ) , tf.convert_to_tensor(__A ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np SCREAMING_SNAKE_CASE__ = [np.ones((1, 3, 5, 5) )] SCREAMING_SNAKE_CASE__ = processor.post_process_masks( __A , np.array(__A ) , np.array(__A ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) SCREAMING_SNAKE_CASE__ = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): SCREAMING_SNAKE_CASE__ = processor.post_process_masks( __A , np.array(__A ) , np.array(__A ) , return_tensors="""tf""" ) @require_vision @require_torchvision class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ = SamImageProcessor() SCREAMING_SNAKE_CASE__ = SamProcessor(__A ) processor.save_pretrained(self.tmpdirname ) def _snake_case ( self :Dict , **__A :str ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **__A ).image_processor def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ = [Image.fromarray(np.moveaxis(__A , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=__A ) SCREAMING_SNAKE_CASE__ = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ = [tf.convert_to_tensor(__A )] SCREAMING_SNAKE_CASE__ = [torch.tensor(__A )] SCREAMING_SNAKE_CASE__ = [[1764, 2646]] SCREAMING_SNAKE_CASE__ = [[683, 1024]] SCREAMING_SNAKE_CASE__ = processor.post_process_masks( __A , __A , __A , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ = processor.post_process_masks( __A , __A , __A , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=__A ) SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = image_processor(__A , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ = processor(images=__A , return_tensors="""pt""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ = image_processor(__A , return_tensors="""tf""" )["""pixel_values"""].numpy() SCREAMING_SNAKE_CASE__ = processor(images=__A , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(__A , __A ) ) self.assertTrue(np.allclose(__A , __A ) ) self.assertTrue(np.allclose(__A , __A ) )
6
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function: {act_fn}''' )
6
1
import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class UpperCamelCase_ ( UpperCamelCase__ ): def __get__( self :Any , __A :Dict , __A :List[Any]=None ) -> List[Any]: """simple docstring""" if obj is None: return self if self.fget is None: raise AttributeError("""unreadable attribute""" ) SCREAMING_SNAKE_CASE__ = """__cached_""" + self.fget.__name__ SCREAMING_SNAKE_CASE__ = getattr(__A , __A , __A ) if cached is None: SCREAMING_SNAKE_CASE__ = self.fget(__A ) setattr(__A , __A , __A ) return cached def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f'''invalid truth value {val!r}''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): if is_torch_fx_proxy(UpperCamelCase__ ): return True if is_torch_available(): import torch if isinstance(UpperCamelCase__ , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(UpperCamelCase__ , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(UpperCamelCase__ , (jnp.ndarray, Tracer) ): return True return isinstance(UpperCamelCase__ , np.ndarray ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): return isinstance(UpperCamelCase__ , np.ndarray ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): return _is_numpy(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict ): import torch return isinstance(UpperCamelCase__ , torch.Tensor ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): return False if not is_torch_available() else _is_torch(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict ): import torch return isinstance(UpperCamelCase__ , torch.device ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): return False if not is_torch_available() else _is_torch_device(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): import torch if isinstance(UpperCamelCase__ , UpperCamelCase__ ): if hasattr(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = getattr(UpperCamelCase__ , UpperCamelCase__ ) else: return False return isinstance(UpperCamelCase__ , torch.dtype ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): import tensorflow as tf return isinstance(UpperCamelCase__ , tf.Tensor ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): return False if not is_tf_available() else _is_tensorflow(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(UpperCamelCase__ , """is_symbolic_tensor""" ): return tf.is_symbolic_tensor(UpperCamelCase__ ) return type(UpperCamelCase__ ) == tf.Tensor def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): return False if not is_tf_available() else _is_tf_symbolic_tensor(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): import jax.numpy as jnp # noqa: F811 return isinstance(UpperCamelCase__ , jnp.ndarray ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): return False if not is_flax_available() else _is_jax(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): if isinstance(UpperCamelCase__ , (dict, UserDict) ): return {k: to_py_obj(UpperCamelCase__ ) for k, v in obj.items()} elif isinstance(UpperCamelCase__ , (list, tuple) ): return [to_py_obj(UpperCamelCase__ ) for o in obj] elif is_tf_tensor(UpperCamelCase__ ): return obj.numpy().tolist() elif is_torch_tensor(UpperCamelCase__ ): return obj.detach().cpu().tolist() elif is_jax_tensor(UpperCamelCase__ ): return np.asarray(UpperCamelCase__ ).tolist() elif isinstance(UpperCamelCase__ , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): if isinstance(UpperCamelCase__ , (dict, UserDict) ): return {k: to_numpy(UpperCamelCase__ ) for k, v in obj.items()} elif isinstance(UpperCamelCase__ , (list, tuple) ): return np.array(UpperCamelCase__ ) elif is_tf_tensor(UpperCamelCase__ ): return obj.numpy() elif is_torch_tensor(UpperCamelCase__ ): return obj.detach().cpu().numpy() elif is_jax_tensor(UpperCamelCase__ ): return np.asarray(UpperCamelCase__ ) else: return obj class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = fields(self ) # Safety and consistency checks if not len(__A ): raise ValueError(f'''{self.__class__.__name__} has no fields.''' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.''' ) SCREAMING_SNAKE_CASE__ = getattr(self , class_fields[0].name ) SCREAMING_SNAKE_CASE__ = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(__A ): if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = first_field.items() SCREAMING_SNAKE_CASE__ = True else: try: SCREAMING_SNAKE_CASE__ = iter(__A ) SCREAMING_SNAKE_CASE__ = True except TypeError: SCREAMING_SNAKE_CASE__ = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(__A ): if ( not isinstance(__A , (list, tuple) ) or not len(__A ) == 2 or not isinstance(element[0] , __A ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute SCREAMING_SNAKE_CASE__ = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).''' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: SCREAMING_SNAKE_CASE__ = element[1] elif first_field is not None: SCREAMING_SNAKE_CASE__ = first_field else: for field in class_fields: SCREAMING_SNAKE_CASE__ = getattr(self , field.name ) if v is not None: SCREAMING_SNAKE_CASE__ = v def __delitem__( self :List[str] , *__A :Tuple , **__A :str ) -> List[str]: """simple docstring""" raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.''' ) def _snake_case ( self :Union[str, Any] , *__A :Union[str, Any] , **__A :List[Any] ) -> Optional[Any]: """simple docstring""" raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.''' ) def _snake_case ( self :Union[str, Any] , *__A :List[Any] , **__A :Union[str, Any] ) -> Tuple: """simple docstring""" raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.''' ) def _snake_case ( self :Optional[Any] , *__A :Union[str, Any] , **__A :Optional[int] ) -> int: """simple docstring""" raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.''' ) def __getitem__( self :List[str] , __A :List[str] ) -> str: """simple docstring""" if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self :List[str] , __A :Dict , __A :Union[str, Any] ) -> Any: """simple docstring""" if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(__A , __A ) super().__setattr__(__A , __A ) def __setitem__( self :Optional[int] , __A :int , __A :Any ) -> Tuple: """simple docstring""" super().__setitem__(__A , __A ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(__A , __A ) def _snake_case ( self :Union[str, Any] ) -> Tuple[Any]: """simple docstring""" return tuple(self[k] for k in self.keys() ) class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @classmethod def _snake_case ( cls :Union[str, Any] , __A :str ) -> str: """simple docstring""" raise ValueError( f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}''' ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "longest" lowerCamelCase_ = "max_length" lowerCamelCase_ = "do_not_pad" class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pt" lowerCamelCase_ = "tf" lowerCamelCase_ = "np" lowerCamelCase_ = "jax" class UpperCamelCase_ : def __init__( self :Union[str, Any] , __A :List[ContextManager] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = context_managers SCREAMING_SNAKE_CASE__ = ExitStack() def __enter__( self :Any ) -> Any: """simple docstring""" for context_manager in self.context_managers: self.stack.enter_context(__A ) def __exit__( self :Any , *__A :Union[str, Any] , **__A :Dict ) -> Tuple: """simple docstring""" self.stack.__exit__(*__A , **__A ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = infer_framework(UpperCamelCase__ ) if framework == "tf": SCREAMING_SNAKE_CASE__ = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": SCREAMING_SNAKE_CASE__ = inspect.signature(model_class.forward ) # PyTorch models else: SCREAMING_SNAKE_CASE__ = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = model_class.__name__ SCREAMING_SNAKE_CASE__ = infer_framework(UpperCamelCase__ ) if framework == "tf": SCREAMING_SNAKE_CASE__ = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": SCREAMING_SNAKE_CASE__ = inspect.signature(model_class.forward ) # PyTorch models else: SCREAMING_SNAKE_CASE__ = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: MutableMapping , UpperCamelCase__: str = "" , UpperCamelCase__: str = "." ): def _flatten_dict(UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple="" , UpperCamelCase__: Optional[Any]="." ): for k, v in d.items(): SCREAMING_SNAKE_CASE__ = str(UpperCamelCase__ ) + delimiter + str(UpperCamelCase__ ) if parent_key else k if v and isinstance(UpperCamelCase__ , UpperCamelCase__ ): yield from flatten_dict(UpperCamelCase__ , UpperCamelCase__ , delimiter=UpperCamelCase__ ).items() else: yield key, v return dict(_flatten_dict(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ) @contextmanager def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: bool = False ): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int]=None ): if is_numpy_array(UpperCamelCase__ ): return np.transpose(UpperCamelCase__ , axes=UpperCamelCase__ ) elif is_torch_tensor(UpperCamelCase__ ): return array.T if axes is None else array.permute(*UpperCamelCase__ ) elif is_tf_tensor(UpperCamelCase__ ): import tensorflow as tf return tf.transpose(UpperCamelCase__ , perm=UpperCamelCase__ ) elif is_jax_tensor(UpperCamelCase__ ): return jnp.transpose(UpperCamelCase__ , axes=UpperCamelCase__ ) else: raise ValueError(f'''Type not supported for transpose: {type(UpperCamelCase__ )}.''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: str ): if is_numpy_array(UpperCamelCase__ ): return np.reshape(UpperCamelCase__ , UpperCamelCase__ ) elif is_torch_tensor(UpperCamelCase__ ): return array.reshape(*UpperCamelCase__ ) elif is_tf_tensor(UpperCamelCase__ ): import tensorflow as tf return tf.reshape(UpperCamelCase__ , UpperCamelCase__ ) elif is_jax_tensor(UpperCamelCase__ ): return jnp.reshape(UpperCamelCase__ , UpperCamelCase__ ) else: raise ValueError(f'''Type not supported for reshape: {type(UpperCamelCase__ )}.''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any]=None ): if is_numpy_array(UpperCamelCase__ ): return np.squeeze(UpperCamelCase__ , axis=UpperCamelCase__ ) elif is_torch_tensor(UpperCamelCase__ ): return array.squeeze() if axis is None else array.squeeze(dim=UpperCamelCase__ ) elif is_tf_tensor(UpperCamelCase__ ): import tensorflow as tf return tf.squeeze(UpperCamelCase__ , axis=UpperCamelCase__ ) elif is_jax_tensor(UpperCamelCase__ ): return jnp.squeeze(UpperCamelCase__ , axis=UpperCamelCase__ ) else: raise ValueError(f'''Type not supported for squeeze: {type(UpperCamelCase__ )}.''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: str ): if is_numpy_array(UpperCamelCase__ ): return np.expand_dims(UpperCamelCase__ , UpperCamelCase__ ) elif is_torch_tensor(UpperCamelCase__ ): return array.unsqueeze(dim=UpperCamelCase__ ) elif is_tf_tensor(UpperCamelCase__ ): import tensorflow as tf return tf.expand_dims(UpperCamelCase__ , axis=UpperCamelCase__ ) elif is_jax_tensor(UpperCamelCase__ ): return jnp.expand_dims(UpperCamelCase__ , axis=UpperCamelCase__ ) else: raise ValueError(f'''Type not supported for expand_dims: {type(UpperCamelCase__ )}.''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): if is_numpy_array(UpperCamelCase__ ): return np.size(UpperCamelCase__ ) elif is_torch_tensor(UpperCamelCase__ ): return array.numel() elif is_tf_tensor(UpperCamelCase__ ): import tensorflow as tf return tf.size(UpperCamelCase__ ) elif is_jax_tensor(UpperCamelCase__ ): return array.size else: raise ValueError(f'''Type not supported for expand_dims: {type(UpperCamelCase__ )}.''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] ): for key, value in auto_map.items(): if isinstance(UpperCamelCase__ , (tuple, list) ): SCREAMING_SNAKE_CASE__ = [f'''{repo_id}--{v}''' if (v is not None and """--""" not in v) else v for v in value] elif value is not None and "--" not in value: SCREAMING_SNAKE_CASE__ = f'''{repo_id}--{value}''' return auto_map def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict ): for base_class in inspect.getmro(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = base_class.__module__ SCREAMING_SNAKE_CASE__ = base_class.__name__ if module.startswith("""tensorflow""" ) or module.startswith("""keras""" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("""torch""" ) or name == "PreTrainedModel": return "pt" elif module.startswith("""flax""" ) or module.startswith("""jax""" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f'''Could not infer framework from class {model_class}.''' )
6
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = SwinConfig.from_pretrained( """microsoft/swin-tiny-patch4-window7-224""" , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) SCREAMING_SNAKE_CASE__ = MaskFormerConfig(backbone_config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" if "ade20k-full" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 847 SCREAMING_SNAKE_CASE__ = """maskformer-ade20k-full-id2label.json""" elif "ade" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 150 SCREAMING_SNAKE_CASE__ = """ade20k-id2label.json""" elif "coco-stuff" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 171 SCREAMING_SNAKE_CASE__ = """maskformer-coco-stuff-id2label.json""" elif "coco" in model_name: # TODO SCREAMING_SNAKE_CASE__ = 133 SCREAMING_SNAKE_CASE__ = """coco-panoptic-id2label.json""" elif "cityscapes" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 19 SCREAMING_SNAKE_CASE__ = """cityscapes-id2label.json""" elif "vistas" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 65 SCREAMING_SNAKE_CASE__ = """mapillary-vistas-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [] # stem # fmt: off rename_keys.append(("""backbone.patch_embed.proj.weight""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.proj.bias""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """model.pixel_level_module.encoder.model.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """model.pixel_level_module.encoder.model.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.layers.{i}.downsample.reduction.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(("""sem_seg_head.layer_4.weight""", """model.pixel_level_module.decoder.fpn.stem.0.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.weight""", """model.pixel_level_module.decoder.fpn.stem.1.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.bias""", """model.pixel_level_module.decoder.fpn.stem.1.bias""") ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((f'''sem_seg_head.adapter_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(("""sem_seg_head.mask_features.weight""", """model.pixel_level_module.decoder.mask_projection.weight""") ) rename_keys.append(("""sem_seg_head.mask_features.bias""", """model.pixel_level_module.decoder.mask_projection.bias""") ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.weight""", """model.transformer_module.decoder.layernorm.weight""") ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.bias""", """model.transformer_module.decoder.layernorm.bias""") ) # heads on top rename_keys.append(("""sem_seg_head.predictor.query_embed.weight""", """model.transformer_module.queries_embedder.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.weight""", """model.transformer_module.input_projection.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.bias""", """model.transformer_module.input_projection.bias""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.weight""", """class_predictor.weight""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.bias""", """class_predictor.bias""") ) for i in range(3 ): rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', f'''mask_embedder.{i}.0.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', f'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE__ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[: dim] SCREAMING_SNAKE_CASE__ = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-dim :] # fmt: on def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): # fmt: off SCREAMING_SNAKE_CASE__ = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # fmt: on def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: bool = False ): SCREAMING_SNAKE_CASE__ = get_maskformer_config(UpperCamelCase__ ) # load original state_dict with open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = data["""model"""] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys SCREAMING_SNAKE_CASE__ = create_rename_keys(UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) read_in_swin_q_k_v(UpperCamelCase__ , config.backbone_config ) read_in_decoder_q_k_v(UpperCamelCase__ , UpperCamelCase__ ) # update to torch tensors for key, value in state_dict.items(): SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) # load 🤗 model SCREAMING_SNAKE_CASE__ = MaskFormerForInstanceSegmentation(UpperCamelCase__ ) model.eval() for name, param in model.named_parameters(): print(UpperCamelCase__ , param.shape ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(UpperCamelCase__ ) == 0, f'''Unexpected keys: {unexpected_keys}''' # verify results SCREAMING_SNAKE_CASE__ = prepare_img() if "vistas" in model_name: SCREAMING_SNAKE_CASE__ = 65 elif "cityscapes" in model_name: SCREAMING_SNAKE_CASE__ = 65_535 else: SCREAMING_SNAKE_CASE__ = 255 SCREAMING_SNAKE_CASE__ = True if """ade""" in model_name else False SCREAMING_SNAKE_CASE__ = MaskFormerImageProcessor(ignore_index=UpperCamelCase__ , reduce_labels=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(UpperCamelCase__ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = model(**UpperCamelCase__ ) print("""Logits:""" , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": SCREAMING_SNAKE_CASE__ = torch.tensor( [[3.6_3_5_3, -4.4_7_7_0, -2.6_0_6_5], [0.5_0_8_1, -4.2_3_9_4, -3.5_3_4_3], [2.1_9_0_9, -5.0_3_5_3, -1.9_3_2_3]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: print("""Pushing model and image processor to the hub...""" ) model.push_to_hub(f'''nielsr/{model_name}''' ) image_processor.push_to_hub(f'''nielsr/{model_name}''' ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='maskformer-swin-tiny-ade', type=str, help=('Name of the MaskFormer model you\'d like to convert',), ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl', type=str, help='Path to the original state dict (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, 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.' ) _lowerCamelCase = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
6
1
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller _lowerCamelCase = 3 def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): print("""Generating primitive root of p""" ) while True: SCREAMING_SNAKE_CASE__ = random.randrange(3 , UpperCamelCase__ ) if pow(UpperCamelCase__ , 2 , UpperCamelCase__ ) == 1: continue if pow(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) == 1: continue return g def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): print("""Generating prime p...""" ) SCREAMING_SNAKE_CASE__ = rabin_miller.generate_large_prime(UpperCamelCase__ ) # select large prime number. SCREAMING_SNAKE_CASE__ = primitive_root(UpperCamelCase__ ) # one primitive root on modulo p. SCREAMING_SNAKE_CASE__ = random.randrange(3 , UpperCamelCase__ ) # private_key -> have to be greater than 2 for safety. SCREAMING_SNAKE_CASE__ = cryptomath.find_mod_inverse(pow(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = (key_size, e_a, e_a, p) SCREAMING_SNAKE_CASE__ = (key_size, d) return public_key, private_key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: int ): if os.path.exists(f'''{name}_pubkey.txt''' ) or os.path.exists(f'''{name}_privkey.txt''' ): print("""\nWARNING:""" ) print( f'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n''' """Use a different name or delete these files and re-run this program.""" ) sys.exit() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = generate_key(UpperCamelCase__ ) print(f'''\nWriting public key to file {name}_pubkey.txt...''' ) with open(f'''{name}_pubkey.txt''' , """w""" ) as fo: fo.write(f'''{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}''' ) print(f'''Writing private key to file {name}_privkey.txt...''' ) with open(f'''{name}_privkey.txt''' , """w""" ) as fo: fo.write(f'''{private_key[0]},{private_key[1]}''' ) def SCREAMING_SNAKE_CASE__ ( ): print("""Making key files...""" ) make_key_files("""elgamal""" , 2_048 ) print("""Key files generation successful""" ) if __name__ == "__main__": main()
6
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCamelCase = 1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py _lowerCamelCase = 0 _lowerCamelCase = 0XE0_00 _lowerCamelCase = 0XE0_01 _lowerCamelCase = 0XE0_02 _lowerCamelCase = 0XE0_03 _lowerCamelCase = 0XE0_04 # Maps special codepoints to human-readable names. _lowerCamelCase = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. _lowerCamelCase = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self :str , __A :str=chr(__A ) , __A :str=chr(__A ) , __A :Dict=chr(__A ) , __A :str=chr(__A ) , __A :Union[str, Any]=chr(__A ) , __A :str=chr(__A ) , __A :int=False , __A :int=2048 , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , model_max_length=__A , **__A , ) # Creates a mapping for looking up the IDs of special symbols. SCREAMING_SNAKE_CASE__ = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): SCREAMING_SNAKE_CASE__ = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. SCREAMING_SNAKE_CASE__ = { codepoint: name for name, codepoint in self._special_codepoints.items() } SCREAMING_SNAKE_CASE__ = UNICODE_VOCAB_SIZE SCREAMING_SNAKE_CASE__ = len(self._special_codepoints ) @property def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" return self._unicode_vocab_size def _snake_case ( self :Tuple , __A :str ) -> List[str]: """simple docstring""" return list(__A ) def _snake_case ( self :Optional[Any] , __A :str ) -> int: """simple docstring""" try: return ord(__A ) except TypeError: raise ValueError(f'''invalid token: \'{token}\'''' ) def _snake_case ( self :str , __A :int ) -> str: """simple docstring""" try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(__A ) except TypeError: raise ValueError(f'''invalid id: {index}''' ) def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Any: """simple docstring""" return "".join(__A ) def _snake_case ( self :Optional[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] + ([0] * len(__A )) + [1] if token_ids_a is not None: result += ([0] * len(__A )) + [1] return result def _snake_case ( self :List[str] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Any: """simple docstring""" return ()
6
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, TensorType _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'openai/imagegpt-small': '', 'openai/imagegpt-medium': '', 'openai/imagegpt-large': '', } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "imagegpt" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self :int , __A :int=512 + 1 , __A :int=32 * 32 , __A :Any=512 , __A :Any=24 , __A :Tuple=8 , __A :Tuple=None , __A :Optional[Any]="quick_gelu" , __A :List[str]=0.1 , __A :Union[str, Any]=0.1 , __A :int=0.1 , __A :Dict=1E-5 , __A :List[str]=0.0_2 , __A :Optional[int]=True , __A :str=True , __A :Union[str, Any]=False , __A :Dict=False , __A :List[Any]=False , **__A :str , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_positions SCREAMING_SNAKE_CASE__ = n_embd SCREAMING_SNAKE_CASE__ = n_layer SCREAMING_SNAKE_CASE__ = n_head SCREAMING_SNAKE_CASE__ = n_inner SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = resid_pdrop SCREAMING_SNAKE_CASE__ = embd_pdrop SCREAMING_SNAKE_CASE__ = attn_pdrop SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = scale_attn_weights SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE__ = reorder_and_upcast_attn SCREAMING_SNAKE_CASE__ = tie_word_embeddings super().__init__(tie_word_embeddings=__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): @property def _snake_case ( self :str ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ] ) def _snake_case ( self :Dict , __A :"FeatureExtractionMixin" , __A :int = 1 , __A :int = -1 , __A :bool = False , __A :Optional["TensorType"] = None , __A :int = 3 , __A :int = 32 , __A :int = 32 , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._generate_dummy_images(__A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = dict(preprocessor(images=__A , return_tensors=__A ) ) return inputs
6
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) _lowerCamelCase = 'bert-base-cased' _lowerCamelCase = 'fp16' _lowerCamelCase = 'bf16' _lowerCamelCase = [FPaa, BFaa] @require_fsdp @require_cuda class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = dict( ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , ) def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = f'''{i + 1}''' SCREAMING_SNAKE_CASE__ = strategy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def _snake_case ( self :int ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = prefetch_policy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = state_dict_type with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoModel.from_pretrained(__A ) for policy in FSDP_AUTO_WRAP_POLICY: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = policy if policy == "TRANSFORMER_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """BertLayer""" elif policy == "SIZE_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """2000""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """TRANSFORMER_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """T5Layer""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() with self.assertRaises(__A ) as cm: fsdp_plugin.set_auto_wrap_policy(__A ) self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """SIZE_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """0""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = mp_dtype with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = Accelerator() if mp_dtype == "fp16": SCREAMING_SNAKE_CASE__ = torch.floataa elif mp_dtype == "bf16": SCREAMING_SNAKE_CASE__ = torch.bfloataa SCREAMING_SNAKE_CASE__ = MixedPrecision(param_dtype=__A , reduce_dtype=__A , buffer_dtype=__A ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __A ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , __A ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__A ) def _snake_case ( self :str ) -> str: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = str(__A ).lower() with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__A ) ) @require_fsdp @require_multi_gpu @slow class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Any ) -> Any: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = 0.8_2 SCREAMING_SNAKE_CASE__ = [ """fsdp_shard_grad_op_transformer_based_wrap""", """fsdp_full_shard_transformer_based_wrap""", ] SCREAMING_SNAKE_CASE__ = { """multi_gpu_fp16""": 3200, """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2000, """fsdp_full_shard_transformer_based_wrap_fp16""": 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] ) def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_performance.py""" ) SCREAMING_SNAKE_CASE__ = ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""] for config in self.performance_configs: SCREAMING_SNAKE_CASE__ = cmd.copy() for i, strategy in enumerate(__A ): if strategy.lower() in config: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "fp32" in config: cmd_config.append("""--mixed_precision=no""" ) else: cmd_config.append("""--mixed_precision=fp16""" ) if "cpu_offload" in config: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--performance_lower_bound={self.performance_lower_bound}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_checkpointing.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp""", """--mixed_precision=fp16""", """--fsdp_transformer_layer_cls_to_wrap=BertLayer""", ] for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = cmd.copy() cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) if strategy != "FULL_SHARD": continue SCREAMING_SNAKE_CASE__ = len(__A ) for state_dict_type in FSDP_STATE_DICT_TYPE: SCREAMING_SNAKE_CASE__ = cmd_config[:state_dict_config_index] cmd_config.append(f'''--fsdp_state_dict_type={state_dict_type}''' ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', """--partial_train_epoch=1""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) SCREAMING_SNAKE_CASE__ = cmd_config[:-1] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdir , """epoch_0""" ) cmd_config.extend( [ f'''--resume_from_checkpoint={resume_from_checkpoint}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): SCREAMING_SNAKE_CASE__ = cmd.copy() if "fp16" in spec: cmd_config.extend(["""--mixed_precision=fp16"""] ) else: cmd_config.extend(["""--mixed_precision=no"""] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["""--use_fsdp"""] ) for i, strategy in enumerate(__A ): if strategy.lower() in spec: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "cpu_offload" in spec: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--peak_memory_upper_bound={peak_mem_upper_bound}''', f'''--n_train={self.n_train}''', f'''--n_val={self.n_val}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() )
6
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = jnp.floataa lowerCamelCase_ = True def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = nn.Dense(5 , dtype=self.dtype ) def __call__( self :List[Any] , *__A :int , **__A :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super().__call__(*__A , **__A ) SCREAMING_SNAKE_CASE__ = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = FlaxBigBirdForNaturalQuestionsModule def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): def cross_entropy(UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=None ): SCREAMING_SNAKE_CASE__ = logits.shape[-1] SCREAMING_SNAKE_CASE__ = (labels[..., None] == jnp.arange(UpperCamelCase__ )[None]).astype("""f4""" ) SCREAMING_SNAKE_CASE__ = jax.nn.log_softmax(UpperCamelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE__ = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: SCREAMING_SNAKE_CASE__ = reduction(UpperCamelCase__ ) return loss SCREAMING_SNAKE_CASE__ = partial(UpperCamelCase__ , reduction=jnp.mean ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class UpperCamelCase_ : lowerCamelCase_ = "google/bigbird-roberta-base" lowerCamelCase_ = 30_00 lowerCamelCase_ = 1_05_00 lowerCamelCase_ = 1_28 lowerCamelCase_ = 3 lowerCamelCase_ = 1 lowerCamelCase_ = 5 # tx_args lowerCamelCase_ = 3e-5 lowerCamelCase_ = 0.0 lowerCamelCase_ = 2_00_00 lowerCamelCase_ = 0.0095 lowerCamelCase_ = "bigbird-roberta-natural-questions" lowerCamelCase_ = "training-expt" lowerCamelCase_ = "data/nq-training.jsonl" lowerCamelCase_ = "data/nq-validation.jsonl" def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(self.base_dir , self.save_dir ) SCREAMING_SNAKE_CASE__ = self.batch_size_per_device * jax.device_count() @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 40_96 # no dynamic padding on TPUs def __call__( self :Optional[Any] , __A :Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.collate_fn(__A ) SCREAMING_SNAKE_CASE__ = jax.tree_util.tree_map(__A , __A ) return batch def _snake_case ( self :List[Any] , __A :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.fetch_inputs(features["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = { """input_ids""": jnp.array(__A , dtype=jnp.intaa ), """attention_mask""": jnp.array(__A , dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ), } return batch def _snake_case ( self :Tuple , __A :list ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self._fetch_inputs(__A ) for ids in input_ids] return zip(*__A ) def _snake_case ( self :List[str] , __A :list ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [1 for _ in range(len(__A ) )] while len(__A ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=None ): if seed is not None: SCREAMING_SNAKE_CASE__ = dataset.shuffle(seed=UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) // batch_size ): SCREAMING_SNAKE_CASE__ = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase__ ) @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] , **UpperCamelCase__: Optional[int] ): def loss_fn(UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=UpperCamelCase__ , dropout_rng=UpperCamelCase__ , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs return state.loss_fn( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = jax.random.split(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.value_and_grad(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = grad_fn(state.params ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean(UpperCamelCase__ , """batch""" ) SCREAMING_SNAKE_CASE__ = state.apply_gradients(grads=UpperCamelCase__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , **UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=state.params , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs SCREAMING_SNAKE_CASE__ = state.loss_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class UpperCamelCase_ ( train_state.TrainState ): lowerCamelCase_ = struct.field(pytree_node=UpperCamelCase__ ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None def _snake_case ( self :List[Any] , __A :str , __A :str , __A :str , __A :Tuple=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = model.params SCREAMING_SNAKE_CASE__ = TrainState.create( apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , ) if ckpt_dir is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = restore_checkpoint(__A , __A ) SCREAMING_SNAKE_CASE__ = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = build_tx(**__A ) SCREAMING_SNAKE_CASE__ = train_state.TrainState( step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = data_collator SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = jax_utils.replicate(__A ) return state def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :int , __A :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.args SCREAMING_SNAKE_CASE__ = len(__A ) // args.batch_size SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ = jax.random.split(__A , jax.device_count() ) for epoch in range(args.max_epochs ): SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , args.batch_size , seed=__A ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc=f'''Running EPOCH-{epoch}''' ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.train_step_fn(__A , __A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(state.step ) SCREAMING_SNAKE_CASE__ = running_loss.item() / i SCREAMING_SNAKE_CASE__ = self.scheduler_fn(state_step - 1 ) SCREAMING_SNAKE_CASE__ = self.evaluate(__A , __A ) SCREAMING_SNAKE_CASE__ = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(__A ) ) self.logger.log(__A , commit=__A ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__A ) def _snake_case ( self :List[str] , __A :Dict , __A :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , self.args.batch_size ) SCREAMING_SNAKE_CASE__ = len(__A ) // self.args.batch_size SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc="""Evaluating ... """ ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ = self.val_step_fn(__A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _snake_case ( self :List[Any] , __A :Any , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(__A ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=""" ... """ ) self.model_save_fn(__A , params=state.params ) with open(os.path.join(__A , """opt_state.msgpack""" ) , """wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__A , """args.joblib""" ) ) joblib.dump(self.data_collator , os.path.join(__A , """data_collator.joblib""" ) ) with open(os.path.join(__A , """training_state.json""" ) , """w""" ) as f: json.dump({"""step""": state.step.item()} , __A ) print("""DONE""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=""" ... """ ) with open(os.path.join(UpperCamelCase__ , """flax_model.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase__ , """opt_state.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.opt_state , f.read() ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """args.joblib""" ) ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """data_collator.joblib""" ) ) with open(os.path.join(UpperCamelCase__ , """training_state.json""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = num_train_steps - warmup_steps SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=UpperCamelCase__ , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=1e-7 , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): def weight_decay_mask(UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = traverse_util.flatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = scheduler_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.adamw(learning_rate=UpperCamelCase__ , weight_decay=UpperCamelCase__ , mask=UpperCamelCase__ ) return tx, lr
6
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig _lowerCamelCase = logging.get_logger(__name__) # General docstring _lowerCamelCase = 'PoolFormerConfig' # Base docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = [1, 512, 7, 7] # Image classification docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = 'tabby, tabby cat' _lowerCamelCase = [ 'sail/poolformer_s12', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: float = 0.0 , UpperCamelCase__: bool = False ): if drop_prob == 0.0 or not training: return input SCREAMING_SNAKE_CASE__ = 1 - drop_prob SCREAMING_SNAKE_CASE__ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets SCREAMING_SNAKE_CASE__ = keep_prob + torch.rand(UpperCamelCase__ , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize SCREAMING_SNAKE_CASE__ = input.div(UpperCamelCase__ ) * random_tensor return output class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Optional[float] = None ) -> None: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = drop_prob def _snake_case ( self :Any , __A :torch.Tensor ) -> torch.Tensor: """simple docstring""" return drop_path(__A , self.drop_prob , self.training ) def _snake_case ( self :Dict ) -> str: """simple docstring""" return "p={}".format(self.drop_prob ) class UpperCamelCase_ ( nn.Module ): def __init__( self :Dict , __A :Optional[Any] , __A :Dict , __A :List[str] , __A :Optional[Any] , __A :Tuple , __A :Optional[Any]=None ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = patch_size if isinstance(__A , collections.abc.Iterable ) else (patch_size, patch_size) SCREAMING_SNAKE_CASE__ = stride if isinstance(__A , collections.abc.Iterable ) else (stride, stride) SCREAMING_SNAKE_CASE__ = padding if isinstance(__A , collections.abc.Iterable ) else (padding, padding) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , kernel_size=__A , stride=__A , padding=__A ) SCREAMING_SNAKE_CASE__ = norm_layer(__A ) if norm_layer else nn.Identity() def _snake_case ( self :Dict , __A :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.projection(__A ) SCREAMING_SNAKE_CASE__ = self.norm(__A ) return embeddings class UpperCamelCase_ ( nn.GroupNorm ): def __init__( self :Dict , __A :Tuple , **__A :Union[str, Any] ) -> Dict: """simple docstring""" super().__init__(1 , __A , **__A ) class UpperCamelCase_ ( nn.Module ): def __init__( self :List[str] , __A :Optional[int] ) -> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.AvgPoolad(__A , stride=1 , padding=pool_size // 2 , count_include_pad=__A ) def _snake_case ( self :Any , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" return self.pool(__A ) - hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Tuple , __A :Dict , __A :int , __A :Any ) -> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if isinstance(config.hidden_act , __A ): SCREAMING_SNAKE_CASE__ = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE__ = config.hidden_act def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.act_fn(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) return hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :str , __A :List[str] , __A :Tuple , __A :Dict , __A :Union[str, Any] , __A :int ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = PoolFormerPooling(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerOutput(__A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) # Useful for training neural nets SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if drop_path > 0.0 else nn.Identity() SCREAMING_SNAKE_CASE__ = config.use_layer_scale if config.use_layer_scale: SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) def _snake_case ( self :Optional[Any] , __A :Optional[int] ) -> str: """simple docstring""" if self.use_layer_scale: SCREAMING_SNAKE_CASE__ = self.pooling(self.before_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = () SCREAMING_SNAKE_CASE__ = self.output(self.after_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs else: SCREAMING_SNAKE_CASE__ = self.drop_path(self.pooling(self.before_norm(__A ) ) ) # First residual connection SCREAMING_SNAKE_CASE__ = pooling_output + hidden_states SCREAMING_SNAKE_CASE__ = () # Second residual connection inside the PoolFormerOutput block SCREAMING_SNAKE_CASE__ = self.drop_path(self.output(self.after_norm(__A ) ) ) SCREAMING_SNAKE_CASE__ = hidden_states + layer_output SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs class UpperCamelCase_ ( nn.Module ): def __init__( self :Union[str, Any] , __A :List[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = config # stochastic depth decay rule SCREAMING_SNAKE_CASE__ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings SCREAMING_SNAKE_CASE__ = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) # Transformer blocks SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers SCREAMING_SNAKE_CASE__ = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__A ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) def _snake_case ( self :str , __A :Tuple , __A :Dict=False , __A :Tuple=True ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = () if output_hidden_states else None SCREAMING_SNAKE_CASE__ = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = layers # Get patch embeddings from hidden_states SCREAMING_SNAKE_CASE__ = embedding_layer(__A ) # Send the embeddings through the blocks for _, blk in enumerate(__A ): SCREAMING_SNAKE_CASE__ = blk(__A ) SCREAMING_SNAKE_CASE__ = layer_outputs[0] if output_hidden_states: SCREAMING_SNAKE_CASE__ = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__A , hidden_states=__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PoolFormerConfig lowerCamelCase_ = "poolformer" lowerCamelCase_ = "pixel_values" lowerCamelCase_ = True def _snake_case ( self :Optional[Any] , __A :Tuple ) -> Dict: """simple docstring""" if isinstance(__A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _snake_case ( self :str , __A :Optional[Any] , __A :Union[str, Any]=False ) -> Any: """simple docstring""" if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = value _lowerCamelCase = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _lowerCamelCase = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n' @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Any ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config SCREAMING_SNAKE_CASE__ = PoolFormerEncoder(__A ) # Initialize weights and apply final processing self.post_init() def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _snake_case ( self :Dict , __A :Optional[torch.FloatTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) SCREAMING_SNAKE_CASE__ = self.encoder( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__A , hidden_states=encoder_outputs.hidden_states , ) class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :Optional[int] ) -> Tuple: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Linear(config.hidden_size , config.hidden_size ) def _snake_case ( self :List[Any] , __A :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dense(__A ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :str , __A :Union[str, Any] ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config.num_labels SCREAMING_SNAKE_CASE__ = PoolFormerModel(__A ) # Final norm SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head SCREAMING_SNAKE_CASE__ = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _snake_case ( self :int , __A :Optional[torch.FloatTensor] = None , __A :Optional[torch.LongTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ = self.poolformer( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = outputs[0] SCREAMING_SNAKE_CASE__ = self.classifier(self.norm(__A ).mean([-2, -1] ) ) SCREAMING_SNAKE_CASE__ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE__ = """single_label_classification""" else: SCREAMING_SNAKE_CASE__ = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE__ = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE__ = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE__ = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) if not return_dict: SCREAMING_SNAKE_CASE__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__A , logits=__A , hidden_states=outputs.hidden_states )
6
1
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position _lowerCamelCase = '2.13.1' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('3.7'): raise ImportWarning( 'To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( 'To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n' 'If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip _lowerCamelCase = concatenate_datasets _lowerCamelCase = DownloadConfig _lowerCamelCase = DownloadManager _lowerCamelCase = DownloadMode _lowerCamelCase = DownloadConfig _lowerCamelCase = DownloadMode _lowerCamelCase = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
6
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device 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 ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Optional[int] , __A :Tuple=13 , __A :Dict=7 , __A :Dict=True , __A :str=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Any=False , __A :Dict=False , __A :Any=False , __A :Tuple=2 , __A :Dict=99 , __A :Optional[Any]=0 , __A :List[str]=32 , __A :Optional[int]=5 , __A :Dict=4 , __A :List[str]=0.1 , __A :Union[str, Any]=0.1 , __A :Tuple=512 , __A :Any=12 , __A :Optional[int]=2 , __A :Union[str, Any]=0.0_2 , __A :Dict=3 , __A :Optional[int]=4 , __A :Any="last" , __A :List[Any]=None , __A :Any=None , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_lengths SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = gelu_activation SCREAMING_SNAKE_CASE__ = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ = causal SCREAMING_SNAKE_CASE__ = asm SCREAMING_SNAKE_CASE__ = n_langs SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_special SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = summary_type SCREAMING_SNAKE_CASE__ = use_proj SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_input_lengths: SCREAMING_SNAKE_CASE__ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , 2 ).float() SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def _snake_case ( self :Tuple , __A :str , __A :int , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[int] , __A :Union[str, Any] , __A :Union[str, Any] , __A :str , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , lengths=__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :str , __A :Any , __A :str , __A :Union[str, Any] , __A :Optional[Any] , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[Any] , __A :Union[str, Any] , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertWithLMHeadModel(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Tuple , __A :Union[str, Any] , __A :Optional[Any] , __A :Dict , __A :Dict , __A :Union[str, Any] , __A :List[str] , __A :Optional[int] , __A :int , __A :str , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnsweringSimple(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :List[str] , __A :Any , __A :int , __A :Tuple , __A :Optional[Any] , __A :Tuple , __A :Optional[int] , __A :str , __A :int , __A :str , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnswering(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , p_mask=__A , ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _snake_case ( self :Optional[int] , __A :str , __A :Optional[int] , __A :Tuple , __A :Dict , __A :List[str] , __A :Tuple , __A :List[str] , __A :Dict , __A :List[str] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self :Optional[Any] , __A :Optional[Any] , __A :Optional[Any] , __A :List[str] , __A :Optional[Any] , __A :int , __A :Tuple , __A :Optional[int] , __A :Union[str, Any] , __A :Dict , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = FlaubertForTokenClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :str , __A :Any , __A :Tuple , __A :List[str] , __A :Tuple , __A :Any , __A :int , __A :Dict , __A :List[str] , __A :Tuple , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = FlaubertForMultipleChoice(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) lowerCamelCase_ = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _snake_case ( self :Any , __A :Optional[int] , __A :Optional[int] , __A :Dict , __A :List[Any] , __A :Tuple ) -> str: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _snake_case ( self :Tuple , __A :List[str] , __A :Optional[int] , __A :Dict=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super()._prepare_for_class(__A , __A , return_labels=__A ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) return inputs_dict def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , emb_dim=37 ) def _snake_case ( self :int ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__A ) def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__A ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__A ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__A ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__A ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__A ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @slow @require_torch_gpu def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = model_class(config=__A ) SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = torch.jit.trace( __A , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__A , os.path.join(__A , """traced_model.pt""" ) ) SCREAMING_SNAKE_CASE__ = torch.jit.load(os.path.join(__A , """traced_model.pt""" ) , map_location=__A ) loaded(inputs_dict["""input_ids"""].to(__A ) , inputs_dict["""attention_mask"""].to(__A ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [[[-2.6_2_5_1, -1.4_2_9_8, -0.0_2_2_7], [-2.8_5_1_0, -1.6_3_8_7, 0.2_2_5_8], [-2.8_1_1_4, -1.1_8_3_2, -0.3_0_6_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=1E-4 ) )
6
1
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :List[str] , __A :str ) -> Optional[int]: """simple docstring""" with open(__A , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) SCREAMING_SNAKE_CASE__ = input_file.read() SCREAMING_SNAKE_CASE__ = regexp.search(__A ) return match def _snake_case ( self :Tuple , __A :str ) -> Optional[Any]: """simple docstring""" with open(__A , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) SCREAMING_SNAKE_CASE__ = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ = regexp.finditer(__A ) SCREAMING_SNAKE_CASE__ = [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 _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(__A ) ): raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' ) def _snake_case ( self :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(__A ) ): raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
6
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple=True ): model.train() SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = F.mse_loss(UpperCamelCase__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[Any]=False ): set_seed(42 ) SCREAMING_SNAKE_CASE__ = RegressionModel() SCREAMING_SNAKE_CASE__ = deepcopy(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) model.to(accelerator.device ) if sched: SCREAMING_SNAKE_CASE__ = AdamW(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = AdamW(params=ddp_model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) # Make a copy of `model` if sched: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): # Test when on a single CPU or GPU that the context manager does nothing SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): # Test on distributed setup that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int=False , UpperCamelCase__: Union[str, Any]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(UpperCamelCase__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple=False , UpperCamelCase__: List[str]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ , UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCamelCase__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n''' SCREAMING_SNAKE_CASE__ = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(UpperCamelCase__ )) if accelerator.num_processes > 1: check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=96 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if iteration < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if batch_num < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(UpperCamelCase__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(UpperCamelCase__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation(UpperCamelCase__ , UpperCamelCase__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" , """2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , """`split_batches=False`, `dispatch_batches=False`**""" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation_with_opt_and_scheduler(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
6
1
import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: str , UpperCamelCase__: int , UpperCamelCase__: List[Any] ): # Initialise PyTorch model SCREAMING_SNAKE_CASE__ = FunnelConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = FunnelBaseModel(UpperCamelCase__ ) if base_model else FunnelModel(UpperCamelCase__ ) # Load weights from tf checkpoint load_tf_weights_in_funnel(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = 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.' ) parser.add_argument( '--base_model', action='store_true', help='Whether you want just the base model (no decoder) or not.' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
6
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCamelCase_ = "AutoTokenizer" def __init__( self :Optional[int] , __A :Optional[Any] , __A :Dict ) -> Dict: """simple docstring""" super().__init__(__A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor def __call__( self :int , __A :str=None , __A :int=None , __A :Union[str, Any]=None , **__A :str ) -> Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :str , *__A :List[str] , **__A :List[str] ) -> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :List[str] , *__A :Any , **__A :Any ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
6
1
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( 'The `image_to_image.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionImg2ImgPipeline` instead.' )
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ = True for i in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = dp[i][j - 1] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE__ = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: SCREAMING_SNAKE_CASE__ = s - 2 * j break return diff
6
1
import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt') _lowerCamelCase = logging.getLogger(__name__) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field( default=1_28 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Train language if it is different from the evaluation language."} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) lowerCamelCase_ = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def SCREAMING_SNAKE_CASE__ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_xnli""" , UpperCamelCase__ ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = training_args.get_process_log_level() logger.setLevel(UpperCamelCase__ ) datasets.utils.logging.set_verbosity(UpperCamelCase__ ) transformers.utils.logging.set_verbosity(UpperCamelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: SCREAMING_SNAKE_CASE__ = load_dataset( """xnli""" , model_args.language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: SCREAMING_SNAKE_CASE__ = load_dataset( """xnli""" , model_args.train_language , split="""train""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ = train_dataset.features["""label"""].names if training_args.do_eval: SCREAMING_SNAKE_CASE__ = load_dataset( """xnli""" , model_args.language , split="""validation""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ = eval_dataset.features["""label"""].names if training_args.do_predict: SCREAMING_SNAKE_CASE__ = load_dataset( """xnli""" , model_args.language , split="""test""" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ = predict_dataset.features["""label"""].names # Labels SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=UpperCamelCase__ , idalabel={str(UpperCamelCase__ ): label for i, label in enumerate(UpperCamelCase__ )} , labelaid={label: i for i, label in enumerate(UpperCamelCase__ )} , finetuning_task="""xnli""" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__ = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch SCREAMING_SNAKE_CASE__ = False def preprocess_function(UpperCamelCase__: Any ): # Tokenize the texts return tokenizer( examples["""premise"""] , examples["""hypothesis"""] , padding=UpperCamelCase__ , max_length=data_args.max_seq_length , truncation=UpperCamelCase__ , ) if training_args.do_train: if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ = train_dataset.select(range(UpperCamelCase__ ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ = train_dataset.map( UpperCamelCase__ , batched=UpperCamelCase__ , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on train dataset""" , ) # Log a few random samples from the training set: for index in random.sample(range(len(UpperCamelCase__ ) ) , 3 ): logger.info(f'''Sample {index} of the training set: {train_dataset[index]}.''' ) if training_args.do_eval: if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ = eval_dataset.select(range(UpperCamelCase__ ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ = eval_dataset.map( UpperCamelCase__ , batched=UpperCamelCase__ , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on validation dataset""" , ) if training_args.do_predict: if data_args.max_predict_samples is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , data_args.max_predict_samples ) SCREAMING_SNAKE_CASE__ = predict_dataset.select(range(UpperCamelCase__ ) ) with training_args.main_process_first(desc="""prediction dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ = predict_dataset.map( UpperCamelCase__ , batched=UpperCamelCase__ , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on prediction dataset""" , ) # Get the metric function SCREAMING_SNAKE_CASE__ = evaluate.load("""xnli""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(UpperCamelCase__: EvalPrediction ): SCREAMING_SNAKE_CASE__ = p.predictions[0] if isinstance(p.predictions , UpperCamelCase__ ) else p.predictions SCREAMING_SNAKE_CASE__ = np.argmax(UpperCamelCase__ , axis=1 ) return metric.compute(predictions=UpperCamelCase__ , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: SCREAMING_SNAKE_CASE__ = default_data_collator elif training_args.fpaa: SCREAMING_SNAKE_CASE__ = DataCollatorWithPadding(UpperCamelCase__ , pad_to_multiple_of=8 ) else: SCREAMING_SNAKE_CASE__ = None # Initialize our Trainer SCREAMING_SNAKE_CASE__ = Trainer( model=UpperCamelCase__ , args=UpperCamelCase__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=UpperCamelCase__ , tokenizer=UpperCamelCase__ , data_collator=UpperCamelCase__ , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ = last_checkpoint SCREAMING_SNAKE_CASE__ = trainer.train(resume_from_checkpoint=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = train_result.metrics SCREAMING_SNAKE_CASE__ = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ , len(UpperCamelCase__ ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , UpperCamelCase__ ) trainer.save_metrics("""train""" , UpperCamelCase__ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ = trainer.evaluate(eval_dataset=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ , len(UpperCamelCase__ ) ) trainer.log_metrics("""eval""" , UpperCamelCase__ ) trainer.save_metrics("""eval""" , UpperCamelCase__ ) # Prediction if training_args.do_predict: logger.info("""*** Predict ***""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = trainer.predict(UpperCamelCase__ , metric_key_prefix="""predict""" ) SCREAMING_SNAKE_CASE__ = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ , len(UpperCamelCase__ ) ) trainer.log_metrics("""predict""" , UpperCamelCase__ ) trainer.save_metrics("""predict""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.argmax(UpperCamelCase__ , axis=1 ) SCREAMING_SNAKE_CASE__ = os.path.join(training_args.output_dir , """predictions.txt""" ) if trainer.is_world_process_zero(): with open(UpperCamelCase__ , """w""" ) as writer: writer.write("""index\tprediction\n""" ) for index, item in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = label_list[item] writer.write(f'''{index}\t{item}\n''' ) if __name__ == "__main__": main()
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
6
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: _lowerCamelCase = None _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), }, 'tokenizer_file': { 'google/bigbird-roberta-base': ( 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json' ), 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json' ), }, } _lowerCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } _lowerCamelCase = '▁' class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = BigBirdTokenizer lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = [] def __init__( self :str , __A :Tuple=None , __A :Optional[Any]=None , __A :Any="<unk>" , __A :Any="<s>" , __A :Union[str, Any]="</s>" , __A :List[str]="<pad>" , __A :Optional[Any]="[SEP]" , __A :str="[MASK]" , __A :Optional[Any]="[CLS]" , **__A :Union[str, Any] , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else unk_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( __A , tokenizer_file=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , **__A , ) SCREAMING_SNAKE_CASE__ = vocab_file SCREAMING_SNAKE_CASE__ = False if not self.vocab_file else True def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _snake_case ( self :Optional[int] , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1] + ([0] * len(__A )) + [1] def _snake_case ( self :Optional[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ): copyfile(self.vocab_file , __A ) return (out_vocab_file,)
6
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = True def __init__( self :Optional[int] , **__A :str ) -> int: """simple docstring""" super().__init__(**__A ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE__ = kwargs.pop("""encoder""" ) SCREAMING_SNAKE_CASE__ = encoder_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""decoder""" ) SCREAMING_SNAKE_CASE__ = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = True @classmethod def _snake_case ( cls :str , __A :PretrainedConfig , __A :PretrainedConfig , **__A :List[str] ) -> PretrainedConfig: """simple docstring""" logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__A ) def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.encoder.to_dict() SCREAMING_SNAKE_CASE__ = self.decoder.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
6
1
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :str=3 , __A :List[Any]=3 , __A :str=("DownEncoderBlock2D",) , __A :Optional[int]=(64,) , __A :str=2 , __A :Optional[Any]=32 , __A :int="silu" , __A :List[Any]=True , ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = torch.nn.Convad( __A , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) # down SCREAMING_SNAKE_CASE__ = block_out_channels[0] for i, down_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_down_block( __A , num_layers=self.layers_per_block , in_channels=__A , out_channels=__A , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , ) self.down_blocks.append(__A ) # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # out SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = 2 * out_channels if double_z else out_channels SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[-1] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :Optional[int] , __A :Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = x SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) if self.training and self.gradient_checkpointing: def create_custom_forward(__A :Tuple ): def custom_forward(*__A :List[Any] ): return module(*__A ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , use_reentrant=__A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , use_reentrant=__A ) else: for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __A ) else: # down for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = down_block(__A ) # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A ) # post-process SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :List[Any]=3 , __A :str=3 , __A :Tuple=("UpDecoderBlock2D",) , __A :Tuple=(64,) , __A :Any=2 , __A :int=32 , __A :Optional[int]="silu" , __A :Optional[Any]="group" , ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = nn.Convad( __A , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) SCREAMING_SNAKE_CASE__ = in_channels if norm_type == """spatial""" else None # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # up SCREAMING_SNAKE_CASE__ = list(reversed(__A ) ) SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[0] for i, up_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_up_block( __A , num_layers=self.layers_per_block + 1 , in_channels=__A , out_channels=__A , prev_output_channel=__A , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , resnet_time_scale_shift=__A , ) self.up_blocks.append(__A ) SCREAMING_SNAKE_CASE__ = output_channel # out if norm_type == "spatial": SCREAMING_SNAKE_CASE__ = SpatialNorm(block_out_channels[0] , __A ) else: SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[0] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :str , __A :Tuple , __A :int=None ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = z SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) SCREAMING_SNAKE_CASE__ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__A :Tuple ): def custom_forward(*__A :List[Any] ): return module(*__A ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A , use_reentrant=__A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , __A , use_reentrant=__A ) else: # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A , __A ) else: # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = up_block(__A , __A ) # post-process if latent_embeds is None: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) else: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A , __A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[int] , __A :Optional[Any] , __A :List[Any] , __A :str , __A :List[str]=None , __A :Optional[Any]="random" , __A :Optional[int]=False , __A :int=True ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = vq_embed_dim SCREAMING_SNAKE_CASE__ = beta SCREAMING_SNAKE_CASE__ = legacy SCREAMING_SNAKE_CASE__ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) SCREAMING_SNAKE_CASE__ = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) SCREAMING_SNAKE_CASE__ = self.used.shape[0] SCREAMING_SNAKE_CASE__ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": SCREAMING_SNAKE_CASE__ = self.re_embed SCREAMING_SNAKE_CASE__ = self.re_embed + 1 print( f'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' f'''Using {self.unknown_index} for unknown indices.''' ) else: SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = sane_index_shape def _snake_case ( self :Tuple , __A :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) SCREAMING_SNAKE_CASE__ = (inds[:, :, None] == used[None, None, ...]).long() SCREAMING_SNAKE_CASE__ = match.argmax(-1 ) SCREAMING_SNAKE_CASE__ = match.sum(2 ) < 1 if self.unknown_index == "random": SCREAMING_SNAKE_CASE__ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: SCREAMING_SNAKE_CASE__ = self.unknown_index return new.reshape(__A ) def _snake_case ( self :Dict , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) if self.re_embed > self.used.shape[0]: # extra token SCREAMING_SNAKE_CASE__ = 0 # simply set to zero SCREAMING_SNAKE_CASE__ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __A ) return back.reshape(__A ) def _snake_case ( self :Optional[int] , __A :List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = z.permute(0 , 2 , 3 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z SCREAMING_SNAKE_CASE__ = torch.argmin(torch.cdist(__A , self.embedding.weight ) , dim=1 ) SCREAMING_SNAKE_CASE__ = self.embedding(__A ).view(z.shape ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # compute loss for embedding if not self.legacy: SCREAMING_SNAKE_CASE__ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: SCREAMING_SNAKE_CASE__ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients SCREAMING_SNAKE_CASE__ = z + (z_q - z).detach() # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.remap_to_used(__A ) SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _snake_case ( self :Union[str, Any] , __A :Dict , __A :Optional[Any] ) -> Dict: """simple docstring""" if self.remap is not None: SCREAMING_SNAKE_CASE__ = indices.reshape(shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.unmap_to_all(__A ) SCREAMING_SNAKE_CASE__ = indices.reshape(-1 ) # flatten again # get quantized latent vectors SCREAMING_SNAKE_CASE__ = self.embedding(__A ) if shape is not None: SCREAMING_SNAKE_CASE__ = z_q.view(__A ) # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , __A :List[str] , __A :Dict=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parameters SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = torch.chunk(__A , 2 , dim=1 ) SCREAMING_SNAKE_CASE__ = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) SCREAMING_SNAKE_CASE__ = deterministic SCREAMING_SNAKE_CASE__ = torch.exp(0.5 * self.logvar ) SCREAMING_SNAKE_CASE__ = torch.exp(self.logvar ) if self.deterministic: SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def _snake_case ( self :Union[str, Any] , __A :Optional[torch.Generator] = None ) -> torch.FloatTensor: """simple docstring""" SCREAMING_SNAKE_CASE__ = randn_tensor( self.mean.shape , generator=__A , device=self.parameters.device , dtype=self.parameters.dtype ) SCREAMING_SNAKE_CASE__ = self.mean + self.std * sample return x def _snake_case ( self :str , __A :Any=None ) -> Union[str, Any]: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def _snake_case ( self :str , __A :Optional[int] , __A :List[Any]=[1, 2, 3] ) -> Any: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) SCREAMING_SNAKE_CASE__ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__A ) def _snake_case ( self :Any ) -> str: """simple docstring""" return self.mean
6
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowerCamelCase_ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"text": Value("string" )} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "text" lowerCamelCase_ = "labels" def _snake_case ( self :Any , __A :Dict ) -> Optional[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] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :str ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
6
1
import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "linear" lowerCamelCase_ = "cosine" lowerCamelCase_ = "cosine_with_restarts" lowerCamelCase_ = "polynomial" lowerCamelCase_ = "constant" lowerCamelCase_ = "constant_with_warmup" lowerCamelCase_ = "piecewise_constant" def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optimizer , UpperCamelCase__: int = -1 ): return LambdaLR(UpperCamelCase__ , lambda UpperCamelCase__ : 1 , last_epoch=UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optimizer , UpperCamelCase__: int , UpperCamelCase__: int = -1 ): def lr_lambda(UpperCamelCase__: int ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1.0 , UpperCamelCase__ ) ) return 1.0 return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , last_epoch=UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optimizer , UpperCamelCase__: str , UpperCamelCase__: int = -1 ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = step_rules.split(""",""" ) for rule_str in rule_list[:-1]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = rule_str.split(""":""" ) SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = float(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = value SCREAMING_SNAKE_CASE__ = float(rule_list[-1] ) def create_rules_function(UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): def rule_func(UpperCamelCase__: int ) -> float: SCREAMING_SNAKE_CASE__ = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(UpperCamelCase__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func SCREAMING_SNAKE_CASE__ = create_rules_function(UpperCamelCase__ , UpperCamelCase__ ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , last_epoch=UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: str , UpperCamelCase__: Dict , UpperCamelCase__: List[str]=-1 ): def lr_lambda(UpperCamelCase__: int ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optimizer , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: float = 0.5 , UpperCamelCase__: int = -1 ): def lr_lambda(UpperCamelCase__: Any ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(UpperCamelCase__ ) * 2.0 * progress )) ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optimizer , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int = 1 , UpperCamelCase__: int = -1 ): def lr_lambda(UpperCamelCase__: Optional[Any] ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(UpperCamelCase__ ) * progress) % 1.0) )) ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: int=1e-7 , UpperCamelCase__: int=1.0 , UpperCamelCase__: Optional[int]=-1 ): SCREAMING_SNAKE_CASE__ = optimizer.defaults["""lr"""] if not (lr_init > lr_end): raise ValueError(f'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' ) def lr_lambda(UpperCamelCase__: int ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: SCREAMING_SNAKE_CASE__ = lr_init - lr_end SCREAMING_SNAKE_CASE__ = num_training_steps - num_warmup_steps SCREAMING_SNAKE_CASE__ = 1 - (current_step - num_warmup_steps) / decay_steps SCREAMING_SNAKE_CASE__ = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _lowerCamelCase = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, SchedulerType] , UpperCamelCase__: Optimizer , UpperCamelCase__: Optional[str] = None , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: int = 1 , UpperCamelCase__: float = 1.0 , UpperCamelCase__: int = -1 , ): SCREAMING_SNAKE_CASE__ = SchedulerType(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(UpperCamelCase__ , last_epoch=UpperCamelCase__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(UpperCamelCase__ , step_rules=UpperCamelCase__ , last_epoch=UpperCamelCase__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f'''{name} requires `num_warmup_steps`, please provide that argument.''' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , last_epoch=UpperCamelCase__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f'''{name} requires `num_training_steps`, please provide that argument.''' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , num_training_steps=UpperCamelCase__ , num_cycles=UpperCamelCase__ , last_epoch=UpperCamelCase__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , num_training_steps=UpperCamelCase__ , power=UpperCamelCase__ , last_epoch=UpperCamelCase__ , ) return schedule_func( UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , num_training_steps=UpperCamelCase__ , last_epoch=UpperCamelCase__ )
6
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = model.config SCREAMING_SNAKE_CASE__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) SCREAMING_SNAKE_CASE__ = MBartConfig( is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , ) return encoder_config, decoder_config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if "encoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" ) if "decoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if name.startswith("""encoder""" ): if "layers" in name: SCREAMING_SNAKE_CASE__ = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "mask" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight""" if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias""" return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_split[3] ) SCREAMING_SNAKE_CASE__ = int(key_split[5] ) SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE__ = val[:dim, :] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ = val[-dim:, :] else: SCREAMING_SNAKE_CASE__ = val[:dim] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: SCREAMING_SNAKE_CASE__ = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): # load original model SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval() # load HuggingFace model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = original_model.state_dict() SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify results on scanned document SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" ) SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" SCREAMING_SNAKE_CASE__ = """When is the coffee break?""" SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>""" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: SCREAMING_SNAKE_CASE__ = """<s_cord>""" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": SCREAMING_SNAKE_CASE__ = """s_cord-v2>""" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>""" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt SCREAMING_SNAKE_CASE__ = """hello world""" else: raise ValueError("""Model name not supported""" ) SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[ """input_ids""" ] SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) # verify encoder hidden states SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) # verify decoder hidden states SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, 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 and processor to the 🤗 hub.', ) _lowerCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
6
1
import os def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str = "input.txt" ): with open(os.path.join(os.path.dirname(UpperCamelCase__ ) , UpperCamelCase__ ) ) as input_file: SCREAMING_SNAKE_CASE__ = [ [int(UpperCamelCase__ ) for element in line.split(""",""" )] for line in input_file.readlines() ] SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = len(matrix[0] ) SCREAMING_SNAKE_CASE__ = [[-1 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = matrix[i][0] for j in range(1 , UpperCamelCase__ ): for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): SCREAMING_SNAKE_CASE__ = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(F'''{solution() = }''')
6
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_dpmpp_2m""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=7.5 , num_inference_steps=15 , output_type="""np""" , use_karras_sigmas=__A , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list , UpperCamelCase__: list , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[0] * n for i in range(UpperCamelCase__ )] for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = y_points[i] for i in range(2 , UpperCamelCase__ ): for j in range(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE__ = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE__ = n return int(UpperCamelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
6
1
from ...configuration_utils import PretrainedConfig _lowerCamelCase = { 'google/tapas-base-finetuned-sqa': ( 'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json' ), 'google/tapas-base-finetuned-wtq': ( 'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json' ), 'google/tapas-base-finetuned-wikisql-supervised': ( 'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json' ), 'google/tapas-base-finetuned-tabfact': ( 'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "tapas" def __init__( self :Tuple , __A :List[Any]=3_0522 , __A :Dict=768 , __A :List[Any]=12 , __A :int=12 , __A :Any=3072 , __A :str="gelu" , __A :Union[str, Any]=0.1 , __A :Optional[Any]=0.1 , __A :Tuple=1024 , __A :Any=[3, 256, 256, 2, 256, 256, 10] , __A :Optional[Any]=0.0_2 , __A :Tuple=1E-12 , __A :Any=0 , __A :Union[str, Any]=1_0.0 , __A :Any=0 , __A :Tuple=1.0 , __A :Optional[int]=None , __A :Dict=1.0 , __A :Optional[Any]=False , __A :Union[str, Any]=None , __A :List[Any]=1.0 , __A :int=1.0 , __A :Optional[int]=False , __A :Optional[int]=False , __A :Tuple="ratio" , __A :List[Any]=None , __A :Optional[int]=None , __A :Any=64 , __A :Tuple=32 , __A :Any=False , __A :List[str]=True , __A :Optional[Any]=False , __A :str=False , __A :List[str]=True , __A :Any=False , __A :Optional[int]=None , __A :Any=None , **__A :Any , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=__A , **__A ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_sizes SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps # Fine-tuning task hyperparameters SCREAMING_SNAKE_CASE__ = positive_label_weight SCREAMING_SNAKE_CASE__ = num_aggregation_labels SCREAMING_SNAKE_CASE__ = aggregation_loss_weight SCREAMING_SNAKE_CASE__ = use_answer_as_supervision SCREAMING_SNAKE_CASE__ = answer_loss_importance SCREAMING_SNAKE_CASE__ = use_normalized_answer_loss SCREAMING_SNAKE_CASE__ = huber_loss_delta SCREAMING_SNAKE_CASE__ = temperature SCREAMING_SNAKE_CASE__ = aggregation_temperature SCREAMING_SNAKE_CASE__ = use_gumbel_for_cells SCREAMING_SNAKE_CASE__ = use_gumbel_for_aggregation SCREAMING_SNAKE_CASE__ = average_approximation_function SCREAMING_SNAKE_CASE__ = cell_selection_preference SCREAMING_SNAKE_CASE__ = answer_loss_cutoff SCREAMING_SNAKE_CASE__ = max_num_rows SCREAMING_SNAKE_CASE__ = max_num_columns SCREAMING_SNAKE_CASE__ = average_logits_per_cell SCREAMING_SNAKE_CASE__ = select_one_column SCREAMING_SNAKE_CASE__ = allow_empty_column_selection SCREAMING_SNAKE_CASE__ = init_cell_selection_weights_to_zero SCREAMING_SNAKE_CASE__ = reset_position_index_per_cell SCREAMING_SNAKE_CASE__ = disable_per_token_loss # Aggregation hyperparameters SCREAMING_SNAKE_CASE__ = aggregation_labels SCREAMING_SNAKE_CASE__ = no_aggregation_label_index if isinstance(self.aggregation_labels , __A ): SCREAMING_SNAKE_CASE__ = {int(__A ): v for k, v in aggregation_labels.items()}
6
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) )
6
1
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 class UpperCamelCase_ : def __init__( self :Optional[Any] , __A :int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [[] for _ in range(__A )] SCREAMING_SNAKE_CASE__ = size def __getitem__( self :Dict , __A :int ) -> Iterator[Edge]: """simple docstring""" return iter(self._graph[vertex] ) @property def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" return self._size def _snake_case ( self :List[Any] , __A :int , __A :int , __A :int ) -> int: """simple docstring""" if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(__A , __A ) ) def _snake_case ( self :List[Any] , __A :int , __A :int ) -> int | None: """simple docstring""" SCREAMING_SNAKE_CASE__ = deque([start_vertex] ) SCREAMING_SNAKE_CASE__ = [None] * self.size SCREAMING_SNAKE_CASE__ = 0 while queue: SCREAMING_SNAKE_CASE__ = queue.popleft() SCREAMING_SNAKE_CASE__ = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: SCREAMING_SNAKE_CASE__ = current_distance + edge.weight SCREAMING_SNAKE_CASE__ = distances[edge.destination_vertex] if ( isinstance(__A , __A ) and new_distance >= dest_vertex_distance ): continue SCREAMING_SNAKE_CASE__ = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
6
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""": """Friday""", """6""": """Saturday""", } SCREAMING_SNAKE_CASE__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(UpperCamelCase__ ) < 11: raise ValueError("""Must be 10 characters long""" ) # Get month SCREAMING_SNAKE_CASE__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("""Month must be between 1 - 12""" ) SCREAMING_SNAKE_CASE__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get day SCREAMING_SNAKE_CASE__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("""Date must be between 1 - 31""" ) # Get second separator SCREAMING_SNAKE_CASE__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get year SCREAMING_SNAKE_CASE__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8_500: raise ValueError( """Year out of range. There has to be some sort of limit...right?""" ) # Get datetime obj for validation SCREAMING_SNAKE_CASE__ = datetime.date(int(UpperCamelCase__ ) , int(UpperCamelCase__ ) , int(UpperCamelCase__ ) ) # Start math if m <= 2: SCREAMING_SNAKE_CASE__ = y - 1 SCREAMING_SNAKE_CASE__ = m + 12 # maths var SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[:2] ) SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[2:] ) SCREAMING_SNAKE_CASE__ = int(2.6 * m - 5.3_9 ) SCREAMING_SNAKE_CASE__ = int(c / 4 ) SCREAMING_SNAKE_CASE__ = int(k / 4 ) SCREAMING_SNAKE_CASE__ = int(d + k ) SCREAMING_SNAKE_CASE__ = int(t + u + v + x ) SCREAMING_SNAKE_CASE__ = int(z - (2 * c) ) SCREAMING_SNAKE_CASE__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" ) # Response SCREAMING_SNAKE_CASE__ = f'''Your date {date_input}, is a {days[str(UpperCamelCase__ )]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) _lowerCamelCase = parser.parse_args() zeller(args.date_input)
6
1
import warnings 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 _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nvidia/segformer-b0-finetuned-ade-512-512': ( 'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "segformer" def __init__( self :Optional[int] , __A :Optional[Any]=3 , __A :Optional[Any]=4 , __A :int=[2, 2, 2, 2] , __A :int=[8, 4, 2, 1] , __A :str=[32, 64, 160, 256] , __A :Optional[int]=[7, 3, 3, 3] , __A :Optional[int]=[4, 2, 2, 2] , __A :int=[1, 2, 5, 8] , __A :List[str]=[4, 4, 4, 4] , __A :Union[str, Any]="gelu" , __A :Tuple=0.0 , __A :int=0.0 , __A :Optional[int]=0.1 , __A :Any=0.0_2 , __A :Union[str, Any]=0.1 , __A :Dict=1E-6 , __A :Optional[int]=256 , __A :Dict=255 , **__A :Any , ) -> Dict: """simple docstring""" super().__init__(**__A ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __A , ) SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = num_encoder_blocks SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = sr_ratios SCREAMING_SNAKE_CASE__ = hidden_sizes SCREAMING_SNAKE_CASE__ = patch_sizes SCREAMING_SNAKE_CASE__ = strides SCREAMING_SNAKE_CASE__ = mlp_ratios SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = classifier_dropout_prob SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = decoder_hidden_size SCREAMING_SNAKE_CASE__ = kwargs.get("""reshape_last_stage""" , __A ) SCREAMING_SNAKE_CASE__ = semantic_loss_ignore_index class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = version.parse("1.11" ) @property def _snake_case ( self :int ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self :Union[str, Any] ) -> float: """simple docstring""" return 1E-4 @property def _snake_case ( self :List[str] ) -> int: """simple docstring""" return 12
6
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30522, type=int) _lowerCamelCase = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: _lowerCamelCase = pickle.load(fp) logger.info('Counting occurrences for MLM.') _lowerCamelCase = Counter() for tk_ids in data: counter.update(tk_ids) _lowerCamelCase = [0] * args.vocab_size for k, v in counter.items(): _lowerCamelCase = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
6
1
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer _lowerCamelCase = ['gpt2'] _lowerCamelCase = 'gpt2' if is_tf_available(): class UpperCamelCase_ ( tf.Module ): def __init__( self :Optional[Any] , __A :Union[str, Any] ) -> List[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = tokenizer SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = TFGPTaLMHeadModel.from_config(__A ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name="""text""" ),) ) def _snake_case ( self :Optional[int] , __A :int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer(__A ) SCREAMING_SNAKE_CASE__ = tokenized["""input_ids"""].to_tensor() SCREAMING_SNAKE_CASE__ = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) SCREAMING_SNAKE_CASE__ = self.model(input_ids=__A , attention_mask=__A )["""logits"""] return outputs @require_tf @require_keras_nlp class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = [GPTaTokenizer.from_pretrained(__A ) for checkpoint in (TOKENIZER_CHECKPOINTS)] SCREAMING_SNAKE_CASE__ = [TFGPTaTokenizer.from_pretrained(__A ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) SCREAMING_SNAKE_CASE__ = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] SCREAMING_SNAKE_CASE__ = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _snake_case ( self :Any ) -> Any: """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: SCREAMING_SNAKE_CASE__ = tokenizer([test_inputs] , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors SCREAMING_SNAKE_CASE__ = python_outputs[key].numpy() SCREAMING_SNAKE_CASE__ = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(__A , tf.intaa ) == tf_outputs_values ) ) @slow def _snake_case ( self :Any ) -> int: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE__ = tf.function(__A ) for test_inputs in self.test_sentences: SCREAMING_SNAKE_CASE__ = tf.constant(__A ) SCREAMING_SNAKE_CASE__ = compiled_tokenizer(__A ) SCREAMING_SNAKE_CASE__ = tf_tokenizer(__A ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE__ = ModelToSave(tokenizer=__A ) SCREAMING_SNAKE_CASE__ = tf.convert_to_tensor([self.test_sentences[0]] ) SCREAMING_SNAKE_CASE__ = model.serving(__A ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: SCREAMING_SNAKE_CASE__ = Path(__A ) / """saved.model""" tf.saved_model.save(__A , __A , signatures={"""serving_default""": model.serving} ) SCREAMING_SNAKE_CASE__ = tf.saved_model.load(__A ) SCREAMING_SNAKE_CASE__ = loaded_model.signatures["""serving_default"""](__A )["""output_0"""] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def _snake_case ( self :Dict ) -> int: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: SCREAMING_SNAKE_CASE__ = tf.convert_to_tensor([self.test_sentences[0]] ) SCREAMING_SNAKE_CASE__ = tf_tokenizer(__A ) # Build model with some sample inputs SCREAMING_SNAKE_CASE__ = tf_tokenizer.get_config() SCREAMING_SNAKE_CASE__ = TFGPTaTokenizer.from_config(__A ) SCREAMING_SNAKE_CASE__ = model_from_config(__A ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run SCREAMING_SNAKE_CASE__ = 12_3123 for max_length in [3, 5, 1024]: SCREAMING_SNAKE_CASE__ = tf.convert_to_tensor([self.test_sentences[0]] ) SCREAMING_SNAKE_CASE__ = tf_tokenizer(__A , max_length=__A ) SCREAMING_SNAKE_CASE__ = out["""input_ids"""].numpy().shape[1] assert out_length == max_length
6
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
1
from math import log from scipy.constants import Boltzmann, physical_constants _lowerCamelCase = 300 # TEMPERATURE (unit = K) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float , ): if donor_conc <= 0: raise ValueError("""Donor concentration should be positive""" ) elif acceptor_conc <= 0: raise ValueError("""Acceptor concentration should be positive""" ) elif intrinsic_conc <= 0: raise ValueError("""Intrinsic concentration should be positive""" ) elif donor_conc <= intrinsic_conc: raise ValueError( """Donor concentration should be greater than intrinsic concentration""" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( """Acceptor concentration should be greater than intrinsic concentration""" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
6
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "OwlViTImageProcessor" lowerCamelCase_ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self :Optional[Any] , __A :int=None , __A :Optional[int]=None , **__A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :str , __A :Dict=None , __A :List[str]=None , __A :str=None , __A :Optional[int]="max_length" , __A :Tuple="np" , **__A :int ) -> Tuple: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(__A , __A ) or (isinstance(__A , __A ) and not isinstance(text[0] , __A )): SCREAMING_SNAKE_CASE__ = [self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )] elif isinstance(__A , __A ) and isinstance(text[0] , __A ): SCREAMING_SNAKE_CASE__ = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ = max([len(__A ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(__A ) != max_num_queries: SCREAMING_SNAKE_CASE__ = t + [""" """] * (max_num_queries - len(__A )) SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , padding=__A , return_tensors=__A , **__A ) encodings.append(__A ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = input_ids SCREAMING_SNAKE_CASE__ = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = self.image_processor( __A , return_tensors=__A , **__A ).pixel_values SCREAMING_SNAKE_CASE__ = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Dict , **__A :Dict ) -> Optional[int]: """simple docstring""" return self.image_processor.post_process(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Dict , **__A :List[str] ) -> Optional[Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*__A , **__A ) def _snake_case ( self :str , *__A :List[str] , **__A :Union[str, Any] ) -> Any: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*__A , **__A ) def _snake_case ( self :Dict , *__A :List[str] , **__A :List[str] ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Dict , *__A :Dict , **__A :List[str] ) -> str: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class @property def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __A , ) return self.image_processor
6
1
import functools def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int] , UpperCamelCase__: list[int] ): # Validation if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not all(isinstance(UpperCamelCase__ , UpperCamelCase__ ) for day in days ): raise ValueError("""The parameter days should be a list of integers""" ) if len(UpperCamelCase__ ) != 3 or not all(isinstance(UpperCamelCase__ , UpperCamelCase__ ) for cost in costs ): raise ValueError("""The parameter costs should be a list of three integers""" ) if len(UpperCamelCase__ ) == 0: return 0 if min(UpperCamelCase__ ) <= 0: raise ValueError("""All days elements should be greater than 0""" ) if max(UpperCamelCase__ ) >= 366: raise ValueError("""All days elements should be less than 366""" ) SCREAMING_SNAKE_CASE__ = set(UpperCamelCase__ ) @functools.cache def dynamic_programming(UpperCamelCase__: int ) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 30 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
6
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self :Union[str, Any] , __A :int = 3 , __A :int = 3 , __A :Tuple[str] = ("DownEncoderBlock2D",) , __A :Tuple[str] = ("UpDecoderBlock2D",) , __A :Tuple[int] = (64,) , __A :int = 1 , __A :str = "silu" , __A :int = 3 , __A :int = 32 , __A :int = 256 , __A :int = 32 , __A :Optional[int] = None , __A :float = 0.1_8_2_1_5 , __A :str = "group" , ) -> Any: """simple docstring""" super().__init__() # pass init params to Encoder SCREAMING_SNAKE_CASE__ = Encoder( in_channels=__A , out_channels=__A , down_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , double_z=__A , ) SCREAMING_SNAKE_CASE__ = vq_embed_dim if vq_embed_dim is not None else latent_channels SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = VectorQuantizer(__A , __A , beta=0.2_5 , remap=__A , sane_index_shape=__A ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) # pass init params to Decoder SCREAMING_SNAKE_CASE__ = Decoder( in_channels=__A , out_channels=__A , up_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , norm_type=__A , ) @apply_forward_hook def _snake_case ( self :Union[str, Any] , __A :torch.FloatTensor , __A :bool = True ) -> VQEncoderOutput: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.encoder(__A ) SCREAMING_SNAKE_CASE__ = self.quant_conv(__A ) if not return_dict: return (h,) return VQEncoderOutput(latents=__A ) @apply_forward_hook def _snake_case ( self :Tuple , __A :torch.FloatTensor , __A :bool = False , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" if not force_not_quantize: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = h SCREAMING_SNAKE_CASE__ = self.post_quant_conv(__A ) SCREAMING_SNAKE_CASE__ = self.decoder(__A , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=__A ) def _snake_case ( self :int , __A :torch.FloatTensor , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample SCREAMING_SNAKE_CASE__ = self.encode(__A ).latents SCREAMING_SNAKE_CASE__ = self.decode(__A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__A )
6
1
from __future__ import annotations _lowerCamelCase = 10 def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) while placement <= max_digit: # declare and initialize empty buckets SCREAMING_SNAKE_CASE__ = [[] for _ in range(UpperCamelCase__ )] # split list_of_ints between the buckets for i in list_of_ints: SCREAMING_SNAKE_CASE__ = int((i / placement) % RADIX ) buckets[tmp].append(UpperCamelCase__ ) # put each buckets' contents into list_of_ints SCREAMING_SNAKE_CASE__ = 0 for b in range(UpperCamelCase__ ): for i in buckets[b]: SCREAMING_SNAKE_CASE__ = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
6
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = jnp.floataa lowerCamelCase_ = True def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = nn.Dense(5 , dtype=self.dtype ) def __call__( self :List[Any] , *__A :int , **__A :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super().__call__(*__A , **__A ) SCREAMING_SNAKE_CASE__ = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = FlaxBigBirdForNaturalQuestionsModule def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): def cross_entropy(UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=None ): SCREAMING_SNAKE_CASE__ = logits.shape[-1] SCREAMING_SNAKE_CASE__ = (labels[..., None] == jnp.arange(UpperCamelCase__ )[None]).astype("""f4""" ) SCREAMING_SNAKE_CASE__ = jax.nn.log_softmax(UpperCamelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE__ = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: SCREAMING_SNAKE_CASE__ = reduction(UpperCamelCase__ ) return loss SCREAMING_SNAKE_CASE__ = partial(UpperCamelCase__ , reduction=jnp.mean ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class UpperCamelCase_ : lowerCamelCase_ = "google/bigbird-roberta-base" lowerCamelCase_ = 30_00 lowerCamelCase_ = 1_05_00 lowerCamelCase_ = 1_28 lowerCamelCase_ = 3 lowerCamelCase_ = 1 lowerCamelCase_ = 5 # tx_args lowerCamelCase_ = 3e-5 lowerCamelCase_ = 0.0 lowerCamelCase_ = 2_00_00 lowerCamelCase_ = 0.0095 lowerCamelCase_ = "bigbird-roberta-natural-questions" lowerCamelCase_ = "training-expt" lowerCamelCase_ = "data/nq-training.jsonl" lowerCamelCase_ = "data/nq-validation.jsonl" def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(self.base_dir , self.save_dir ) SCREAMING_SNAKE_CASE__ = self.batch_size_per_device * jax.device_count() @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 40_96 # no dynamic padding on TPUs def __call__( self :Optional[Any] , __A :Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.collate_fn(__A ) SCREAMING_SNAKE_CASE__ = jax.tree_util.tree_map(__A , __A ) return batch def _snake_case ( self :List[Any] , __A :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.fetch_inputs(features["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = { """input_ids""": jnp.array(__A , dtype=jnp.intaa ), """attention_mask""": jnp.array(__A , dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ), } return batch def _snake_case ( self :Tuple , __A :list ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self._fetch_inputs(__A ) for ids in input_ids] return zip(*__A ) def _snake_case ( self :List[str] , __A :list ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [1 for _ in range(len(__A ) )] while len(__A ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=None ): if seed is not None: SCREAMING_SNAKE_CASE__ = dataset.shuffle(seed=UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) // batch_size ): SCREAMING_SNAKE_CASE__ = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase__ ) @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] , **UpperCamelCase__: Optional[int] ): def loss_fn(UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=UpperCamelCase__ , dropout_rng=UpperCamelCase__ , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs return state.loss_fn( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = jax.random.split(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.value_and_grad(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = grad_fn(state.params ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean(UpperCamelCase__ , """batch""" ) SCREAMING_SNAKE_CASE__ = state.apply_gradients(grads=UpperCamelCase__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , **UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=state.params , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs SCREAMING_SNAKE_CASE__ = state.loss_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class UpperCamelCase_ ( train_state.TrainState ): lowerCamelCase_ = struct.field(pytree_node=UpperCamelCase__ ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None def _snake_case ( self :List[Any] , __A :str , __A :str , __A :str , __A :Tuple=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = model.params SCREAMING_SNAKE_CASE__ = TrainState.create( apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , ) if ckpt_dir is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = restore_checkpoint(__A , __A ) SCREAMING_SNAKE_CASE__ = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = build_tx(**__A ) SCREAMING_SNAKE_CASE__ = train_state.TrainState( step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = data_collator SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = jax_utils.replicate(__A ) return state def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :int , __A :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.args SCREAMING_SNAKE_CASE__ = len(__A ) // args.batch_size SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ = jax.random.split(__A , jax.device_count() ) for epoch in range(args.max_epochs ): SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , args.batch_size , seed=__A ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc=f'''Running EPOCH-{epoch}''' ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.train_step_fn(__A , __A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(state.step ) SCREAMING_SNAKE_CASE__ = running_loss.item() / i SCREAMING_SNAKE_CASE__ = self.scheduler_fn(state_step - 1 ) SCREAMING_SNAKE_CASE__ = self.evaluate(__A , __A ) SCREAMING_SNAKE_CASE__ = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(__A ) ) self.logger.log(__A , commit=__A ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__A ) def _snake_case ( self :List[str] , __A :Dict , __A :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , self.args.batch_size ) SCREAMING_SNAKE_CASE__ = len(__A ) // self.args.batch_size SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc="""Evaluating ... """ ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ = self.val_step_fn(__A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _snake_case ( self :List[Any] , __A :Any , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(__A ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=""" ... """ ) self.model_save_fn(__A , params=state.params ) with open(os.path.join(__A , """opt_state.msgpack""" ) , """wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__A , """args.joblib""" ) ) joblib.dump(self.data_collator , os.path.join(__A , """data_collator.joblib""" ) ) with open(os.path.join(__A , """training_state.json""" ) , """w""" ) as f: json.dump({"""step""": state.step.item()} , __A ) print("""DONE""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=""" ... """ ) with open(os.path.join(UpperCamelCase__ , """flax_model.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase__ , """opt_state.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.opt_state , f.read() ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """args.joblib""" ) ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """data_collator.joblib""" ) ) with open(os.path.join(UpperCamelCase__ , """training_state.json""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = num_train_steps - warmup_steps SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=UpperCamelCase__ , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=1e-7 , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): def weight_decay_mask(UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = traverse_util.flatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = scheduler_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.adamw(learning_rate=UpperCamelCase__ , weight_decay=UpperCamelCase__ , mask=UpperCamelCase__ ) return tx, lr
6
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = DPTConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE__ = 1_024 SCREAMING_SNAKE_CASE__ = 4_096 SCREAMING_SNAKE_CASE__ = 24 SCREAMING_SNAKE_CASE__ = 16 SCREAMING_SNAKE_CASE__ = [5, 11, 17, 23] SCREAMING_SNAKE_CASE__ = [256, 512, 1_024, 1_024] SCREAMING_SNAKE_CASE__ = (1, 384, 384) if "ade" in checkpoint_url: SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = 150 SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = """ade20k-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(cached_download(hf_hub_url(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = [1, 150, 480, 480] return config, expected_shape def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.model""" , """dpt.encoder""" ) if "pretrained.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.model""" , """dpt.embeddings""" ) if "patch_embed" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed""" , """patch_embeddings""" ) if "pos_embed" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pos_embed""" , """position_embeddings""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "proj" in name and "project" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""proj""" , """projection""" ) if "blocks" in name: SCREAMING_SNAKE_CASE__ = name.replace("""blocks""" , """layer""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "scratch.output_conv" in name: SCREAMING_SNAKE_CASE__ = name.replace("""scratch.output_conv""" , """head""" ) if "scratch" in name: SCREAMING_SNAKE_CASE__ = name.replace("""scratch""" , """neck""" ) if "layer1_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer1_rn""" , """convs.0""" ) if "layer2_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer2_rn""" , """convs.1""" ) if "layer3_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer3_rn""" , """convs.2""" ) if "layer4_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer4_rn""" , """convs.3""" ) if "refinenet" in name: SCREAMING_SNAKE_CASE__ = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 SCREAMING_SNAKE_CASE__ = name.replace(f'''refinenet{layer_idx}''' , f'''fusion_stage.layers.{abs(layer_idx-4 )}''' ) if "out_conv" in name: SCREAMING_SNAKE_CASE__ = name.replace("""out_conv""" , """projection""" ) if "resConfUnit1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""resConfUnit1""" , """residual_layer1""" ) if "resConfUnit2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""resConfUnit2""" , """residual_layer2""" ) if "conv1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""conv1""" , """convolution1""" ) if "conv2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""conv2""" , """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess1.0.project.0""" , """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess2.0.project.0""" , """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess3.0.project.0""" , """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess4.0.project.0""" , """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess1.3""" , """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess1.4""" , """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess2.3""" , """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess2.4""" , """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess3.3""" , """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess4.3""" , """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess4.4""" , """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained""" , """dpt""" ) if "bn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""bn""" , """batch_norm""" ) if "head" in name: SCREAMING_SNAKE_CASE__ = name.replace("""head""" , """head.head""" ) if "encoder.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.norm""" , """layernorm""" ) if "auxlayer" in name: SCREAMING_SNAKE_CASE__ = name.replace("""auxlayer""" , """auxiliary_head.head""" ) return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: List[str] ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''dpt.encoder.layer.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''dpt.encoder.layer.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: config.hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-config.hidden_size :] def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: str , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_dpt_config(UpperCamelCase__ ) # load original state_dict from URL SCREAMING_SNAKE_CASE__ = torch.hub.load_state_dict_from_url(UpperCamelCase__ , map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(UpperCamelCase__ ) # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = state_dict.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val # read in qkv matrices read_in_q_k_v(UpperCamelCase__ , UpperCamelCase__ ) # load HuggingFace model SCREAMING_SNAKE_CASE__ = DPTForSemanticSegmentation(UpperCamelCase__ ) if """ade""" in checkpoint_url else DPTForDepthEstimation(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Check outputs on an image SCREAMING_SNAKE_CASE__ = 480 if """ade""" in checkpoint_url else 384 SCREAMING_SNAKE_CASE__ = DPTImageProcessor(size=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(UpperCamelCase__ , return_tensors="""pt""" ) # forward pass SCREAMING_SNAKE_CASE__ = model(**UpperCamelCase__ ).logits if """ade""" in checkpoint_url else model(**UpperCamelCase__ ).predicted_depth # Assert logits SCREAMING_SNAKE_CASE__ = torch.tensor([[6.3_1_9_9, 6.3_6_2_9, 6.4_1_4_8], [6.3_8_5_0, 6.3_6_1_5, 6.4_1_6_6], [6.3_5_1_9, 6.3_1_7_6, 6.3_5_7_5]] ) if "ade" in checkpoint_url: SCREAMING_SNAKE_CASE__ = torch.tensor([[4.0_4_8_0, 4.2_4_2_0, 4.4_3_6_0], [4.3_1_2_4, 4.5_6_9_3, 4.8_2_6_1], [4.5_7_6_8, 4.8_9_6_5, 5.2_1_6_3]] ) assert outputs.shape == torch.Size(UpperCamelCase__ ) assert ( torch.allclose(outputs[0, 0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3] , UpperCamelCase__ ) ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(UpperCamelCase__ , UpperCamelCase__ ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=UpperCamelCase__ , ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCamelCase__ , UpperCamelCase__ ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase__ , ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt', type=str, help='URL of the original DPT checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', action='store_true', ) parser.add_argument( '--model_name', default='dpt-large', type=str, help='Name of the model, in case you\'re pushing to the hub.', ) _lowerCamelCase = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
6
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function: {act_fn}''' )
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 10 , UpperCamelCase__: int = 1_000 , UpperCamelCase__: bool = True ): assert ( isinstance(UpperCamelCase__ , UpperCamelCase__ ) and isinstance(UpperCamelCase__ , UpperCamelCase__ ) and isinstance(UpperCamelCase__ , UpperCamelCase__ ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("""Invalid value for min_val or max_val (min_value < max_value)""" ) return min_val if option else max_val def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int ): return int((number_a + number_a) / 2 ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int ): assert ( isinstance(UpperCamelCase__ , UpperCamelCase__ ) and isinstance(UpperCamelCase__ , UpperCamelCase__ ) and isinstance(UpperCamelCase__ , UpperCamelCase__ ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("""argument value for lower and higher must be(lower > higher)""" ) if not lower < to_guess < higher: raise ValueError( """guess value must be within the range of lower and higher value""" ) def answer(UpperCamelCase__: int ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("""started...""" ) SCREAMING_SNAKE_CASE__ = lower SCREAMING_SNAKE_CASE__ = higher SCREAMING_SNAKE_CASE__ = [] while True: SCREAMING_SNAKE_CASE__ = get_avg(UpperCamelCase__ , UpperCamelCase__ ) last_numbers.append(UpperCamelCase__ ) if answer(UpperCamelCase__ ) == "low": SCREAMING_SNAKE_CASE__ = number elif answer(UpperCamelCase__ ) == "high": SCREAMING_SNAKE_CASE__ = number else: break print(f'''guess the number : {last_numbers[-1]}''' ) print(f'''details : {last_numbers!s}''' ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = int(input("""Enter lower value : """ ).strip() ) SCREAMING_SNAKE_CASE__ = int(input("""Enter high value : """ ).strip() ) SCREAMING_SNAKE_CASE__ = int(input("""Enter value to guess : """ ).strip() ) guess_the_number(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
6
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = SwinConfig.from_pretrained( """microsoft/swin-tiny-patch4-window7-224""" , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) SCREAMING_SNAKE_CASE__ = MaskFormerConfig(backbone_config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" if "ade20k-full" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 847 SCREAMING_SNAKE_CASE__ = """maskformer-ade20k-full-id2label.json""" elif "ade" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 150 SCREAMING_SNAKE_CASE__ = """ade20k-id2label.json""" elif "coco-stuff" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 171 SCREAMING_SNAKE_CASE__ = """maskformer-coco-stuff-id2label.json""" elif "coco" in model_name: # TODO SCREAMING_SNAKE_CASE__ = 133 SCREAMING_SNAKE_CASE__ = """coco-panoptic-id2label.json""" elif "cityscapes" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 19 SCREAMING_SNAKE_CASE__ = """cityscapes-id2label.json""" elif "vistas" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 65 SCREAMING_SNAKE_CASE__ = """mapillary-vistas-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [] # stem # fmt: off rename_keys.append(("""backbone.patch_embed.proj.weight""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.proj.bias""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """model.pixel_level_module.encoder.model.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """model.pixel_level_module.encoder.model.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.layers.{i}.downsample.reduction.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(("""sem_seg_head.layer_4.weight""", """model.pixel_level_module.decoder.fpn.stem.0.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.weight""", """model.pixel_level_module.decoder.fpn.stem.1.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.bias""", """model.pixel_level_module.decoder.fpn.stem.1.bias""") ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((f'''sem_seg_head.adapter_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(("""sem_seg_head.mask_features.weight""", """model.pixel_level_module.decoder.mask_projection.weight""") ) rename_keys.append(("""sem_seg_head.mask_features.bias""", """model.pixel_level_module.decoder.mask_projection.bias""") ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.weight""", """model.transformer_module.decoder.layernorm.weight""") ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.bias""", """model.transformer_module.decoder.layernorm.bias""") ) # heads on top rename_keys.append(("""sem_seg_head.predictor.query_embed.weight""", """model.transformer_module.queries_embedder.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.weight""", """model.transformer_module.input_projection.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.bias""", """model.transformer_module.input_projection.bias""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.weight""", """class_predictor.weight""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.bias""", """class_predictor.bias""") ) for i in range(3 ): rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', f'''mask_embedder.{i}.0.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', f'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE__ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[: dim] SCREAMING_SNAKE_CASE__ = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-dim :] # fmt: on def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): # fmt: off SCREAMING_SNAKE_CASE__ = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # fmt: on def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: bool = False ): SCREAMING_SNAKE_CASE__ = get_maskformer_config(UpperCamelCase__ ) # load original state_dict with open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = data["""model"""] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys SCREAMING_SNAKE_CASE__ = create_rename_keys(UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) read_in_swin_q_k_v(UpperCamelCase__ , config.backbone_config ) read_in_decoder_q_k_v(UpperCamelCase__ , UpperCamelCase__ ) # update to torch tensors for key, value in state_dict.items(): SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) # load 🤗 model SCREAMING_SNAKE_CASE__ = MaskFormerForInstanceSegmentation(UpperCamelCase__ ) model.eval() for name, param in model.named_parameters(): print(UpperCamelCase__ , param.shape ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(UpperCamelCase__ ) == 0, f'''Unexpected keys: {unexpected_keys}''' # verify results SCREAMING_SNAKE_CASE__ = prepare_img() if "vistas" in model_name: SCREAMING_SNAKE_CASE__ = 65 elif "cityscapes" in model_name: SCREAMING_SNAKE_CASE__ = 65_535 else: SCREAMING_SNAKE_CASE__ = 255 SCREAMING_SNAKE_CASE__ = True if """ade""" in model_name else False SCREAMING_SNAKE_CASE__ = MaskFormerImageProcessor(ignore_index=UpperCamelCase__ , reduce_labels=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(UpperCamelCase__ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = model(**UpperCamelCase__ ) print("""Logits:""" , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": SCREAMING_SNAKE_CASE__ = torch.tensor( [[3.6_3_5_3, -4.4_7_7_0, -2.6_0_6_5], [0.5_0_8_1, -4.2_3_9_4, -3.5_3_4_3], [2.1_9_0_9, -5.0_3_5_3, -1.9_3_2_3]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: print("""Pushing model and image processor to the hub...""" ) model.push_to_hub(f'''nielsr/{model_name}''' ) image_processor.push_to_hub(f'''nielsr/{model_name}''' ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='maskformer-swin-tiny-ade', type=str, help=('Name of the MaskFormer model you\'d like to convert',), ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl', type=str, help='Path to the original state dict (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, 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.' ) _lowerCamelCase = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
6
1
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict ): return (data["data"], data["target"]) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: np.ndarray , UpperCamelCase__: np.ndarray , UpperCamelCase__: np.ndarray ): SCREAMING_SNAKE_CASE__ = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(UpperCamelCase__ , UpperCamelCase__ ) # Predict target for test data SCREAMING_SNAKE_CASE__ = xgb.predict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = predictions.reshape(len(UpperCamelCase__ ) , 1 ) return predictions def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = fetch_california_housing() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = data_handling(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = train_test_split( UpperCamelCase__ , UpperCamelCase__ , test_size=0.2_5 , random_state=1 ) SCREAMING_SNAKE_CASE__ = xgboost(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Error printing print(f'''Mean Absolute Error : {mean_absolute_error(UpperCamelCase__ , UpperCamelCase__ )}''' ) print(f'''Mean Square Error : {mean_squared_error(UpperCamelCase__ , UpperCamelCase__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
6
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCamelCase = 1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py _lowerCamelCase = 0 _lowerCamelCase = 0XE0_00 _lowerCamelCase = 0XE0_01 _lowerCamelCase = 0XE0_02 _lowerCamelCase = 0XE0_03 _lowerCamelCase = 0XE0_04 # Maps special codepoints to human-readable names. _lowerCamelCase = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. _lowerCamelCase = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self :str , __A :str=chr(__A ) , __A :str=chr(__A ) , __A :Dict=chr(__A ) , __A :str=chr(__A ) , __A :Union[str, Any]=chr(__A ) , __A :str=chr(__A ) , __A :int=False , __A :int=2048 , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , model_max_length=__A , **__A , ) # Creates a mapping for looking up the IDs of special symbols. SCREAMING_SNAKE_CASE__ = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): SCREAMING_SNAKE_CASE__ = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. SCREAMING_SNAKE_CASE__ = { codepoint: name for name, codepoint in self._special_codepoints.items() } SCREAMING_SNAKE_CASE__ = UNICODE_VOCAB_SIZE SCREAMING_SNAKE_CASE__ = len(self._special_codepoints ) @property def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" return self._unicode_vocab_size def _snake_case ( self :Tuple , __A :str ) -> List[str]: """simple docstring""" return list(__A ) def _snake_case ( self :Optional[Any] , __A :str ) -> int: """simple docstring""" try: return ord(__A ) except TypeError: raise ValueError(f'''invalid token: \'{token}\'''' ) def _snake_case ( self :str , __A :int ) -> str: """simple docstring""" try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(__A ) except TypeError: raise ValueError(f'''invalid id: {index}''' ) def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Any: """simple docstring""" return "".join(__A ) def _snake_case ( self :Optional[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] + ([0] * len(__A )) + [1] if token_ids_a is not None: result += ([0] * len(__A )) + [1] return result def _snake_case ( self :List[str] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Any: """simple docstring""" return ()
6
1
# 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 vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES _lowerCamelCase = 'tiny-wmt19-en-ru' # Build # borrowed from a test _lowerCamelCase = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] _lowerCamelCase = dict(zip(vocab, range(len(vocab)))) _lowerCamelCase = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] with tempfile.TemporaryDirectory() as tmpdirname: _lowerCamelCase = Path(tmpdirname) _lowerCamelCase = build_dir / VOCAB_FILES_NAMES['src_vocab_file'] _lowerCamelCase = build_dir / VOCAB_FILES_NAMES['tgt_vocab_file'] _lowerCamelCase = build_dir / VOCAB_FILES_NAMES['merges_file'] with open(src_vocab_file, 'w') as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, 'w') as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, 'w') as fp: fp.write('\n'.join(merges)) _lowerCamelCase = FSMTTokenizer( langs=['en', 'ru'], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) _lowerCamelCase = FSMTConfig( langs=['ru', 'en'], src_vocab_size=1000, tgt_vocab_size=1000, 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, ) _lowerCamelCase = FSMTForConditionalGeneration(config) print(F'''num of params {tiny_model.num_parameters()}''') # Test _lowerCamelCase = tokenizer(['Making tiny model'], return_tensors='pt') _lowerCamelCase = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save 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-ru
6
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) _lowerCamelCase = 'bert-base-cased' _lowerCamelCase = 'fp16' _lowerCamelCase = 'bf16' _lowerCamelCase = [FPaa, BFaa] @require_fsdp @require_cuda class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = dict( ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , ) def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = f'''{i + 1}''' SCREAMING_SNAKE_CASE__ = strategy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def _snake_case ( self :int ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = prefetch_policy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = state_dict_type with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoModel.from_pretrained(__A ) for policy in FSDP_AUTO_WRAP_POLICY: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = policy if policy == "TRANSFORMER_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """BertLayer""" elif policy == "SIZE_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """2000""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """TRANSFORMER_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """T5Layer""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() with self.assertRaises(__A ) as cm: fsdp_plugin.set_auto_wrap_policy(__A ) self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """SIZE_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """0""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = mp_dtype with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = Accelerator() if mp_dtype == "fp16": SCREAMING_SNAKE_CASE__ = torch.floataa elif mp_dtype == "bf16": SCREAMING_SNAKE_CASE__ = torch.bfloataa SCREAMING_SNAKE_CASE__ = MixedPrecision(param_dtype=__A , reduce_dtype=__A , buffer_dtype=__A ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __A ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , __A ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__A ) def _snake_case ( self :str ) -> str: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = str(__A ).lower() with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__A ) ) @require_fsdp @require_multi_gpu @slow class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Any ) -> Any: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = 0.8_2 SCREAMING_SNAKE_CASE__ = [ """fsdp_shard_grad_op_transformer_based_wrap""", """fsdp_full_shard_transformer_based_wrap""", ] SCREAMING_SNAKE_CASE__ = { """multi_gpu_fp16""": 3200, """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2000, """fsdp_full_shard_transformer_based_wrap_fp16""": 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] ) def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_performance.py""" ) SCREAMING_SNAKE_CASE__ = ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""] for config in self.performance_configs: SCREAMING_SNAKE_CASE__ = cmd.copy() for i, strategy in enumerate(__A ): if strategy.lower() in config: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "fp32" in config: cmd_config.append("""--mixed_precision=no""" ) else: cmd_config.append("""--mixed_precision=fp16""" ) if "cpu_offload" in config: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--performance_lower_bound={self.performance_lower_bound}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_checkpointing.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp""", """--mixed_precision=fp16""", """--fsdp_transformer_layer_cls_to_wrap=BertLayer""", ] for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = cmd.copy() cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) if strategy != "FULL_SHARD": continue SCREAMING_SNAKE_CASE__ = len(__A ) for state_dict_type in FSDP_STATE_DICT_TYPE: SCREAMING_SNAKE_CASE__ = cmd_config[:state_dict_config_index] cmd_config.append(f'''--fsdp_state_dict_type={state_dict_type}''' ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', """--partial_train_epoch=1""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) SCREAMING_SNAKE_CASE__ = cmd_config[:-1] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdir , """epoch_0""" ) cmd_config.extend( [ f'''--resume_from_checkpoint={resume_from_checkpoint}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): SCREAMING_SNAKE_CASE__ = cmd.copy() if "fp16" in spec: cmd_config.extend(["""--mixed_precision=fp16"""] ) else: cmd_config.extend(["""--mixed_precision=no"""] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["""--use_fsdp"""] ) for i, strategy in enumerate(__A ): if strategy.lower() in spec: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "cpu_offload" in spec: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--peak_memory_upper_bound={peak_mem_upper_bound}''', f'''--n_train={self.n_train}''', f'''--n_val={self.n_val}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() )
6
1
import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) _lowerCamelCase = { 'iou_prediction_head.layers.0': 'iou_prediction_head.proj_in', 'iou_prediction_head.layers.1': 'iou_prediction_head.layers.0', 'iou_prediction_head.layers.2': 'iou_prediction_head.proj_out', 'mask_decoder.output_upscaling.0': 'mask_decoder.upscale_conv1', 'mask_decoder.output_upscaling.1': 'mask_decoder.upscale_layer_norm', 'mask_decoder.output_upscaling.3': 'mask_decoder.upscale_conv2', 'mask_downscaling.0': 'mask_embed.conv1', 'mask_downscaling.1': 'mask_embed.layer_norm1', 'mask_downscaling.3': 'mask_embed.conv2', 'mask_downscaling.4': 'mask_embed.layer_norm2', 'mask_downscaling.6': 'mask_embed.conv3', 'point_embeddings': 'point_embed', 'pe_layer.positional_encoding_gaussian_matrix': 'shared_embedding.positional_embedding', 'image_encoder': 'vision_encoder', 'neck.0': 'neck.conv1', 'neck.1': 'neck.layer_norm1', 'neck.2': 'neck.conv2', 'neck.3': 'neck.layer_norm2', 'patch_embed.proj': 'patch_embed.projection', '.norm': '.layer_norm', 'blocks': 'layers', } def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = {} state_dict.pop("""pixel_mean""" , UpperCamelCase__ ) state_dict.pop("""pixel_std""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = R""".*.output_hypernetworks_mlps.(\d+).layers.(\d+).*""" for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , UpperCamelCase__ ) if re.match(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = int(re.match(UpperCamelCase__ , UpperCamelCase__ ).group(2 ) ) if layer_nb == 0: SCREAMING_SNAKE_CASE__ = key.replace("""layers.0""" , """proj_in""" ) elif layer_nb == 1: SCREAMING_SNAKE_CASE__ = key.replace("""layers.1""" , """layers.0""" ) elif layer_nb == 2: SCREAMING_SNAKE_CASE__ = key.replace("""layers.2""" , """proj_out""" ) SCREAMING_SNAKE_CASE__ = value SCREAMING_SNAKE_CASE__ = model_state_dict[ """prompt_encoder.shared_embedding.positional_embedding""" ] return model_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple , UpperCamelCase__: int , UpperCamelCase__: Tuple="ybelkada/segment-anything" ): SCREAMING_SNAKE_CASE__ = hf_hub_download(UpperCamelCase__ , f'''checkpoints/{model_name}.pth''' ) if "sam_vit_b" in model_name: SCREAMING_SNAKE_CASE__ = SamConfig() elif "sam_vit_l" in model_name: SCREAMING_SNAKE_CASE__ = SamVisionConfig( hidden_size=1_024 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , ) SCREAMING_SNAKE_CASE__ = SamConfig( vision_config=UpperCamelCase__ , ) elif "sam_vit_h" in model_name: SCREAMING_SNAKE_CASE__ = SamVisionConfig( hidden_size=1_280 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , ) SCREAMING_SNAKE_CASE__ = SamConfig( vision_config=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ = replace_keys(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = SamImageProcessor() SCREAMING_SNAKE_CASE__ = SamProcessor(image_processor=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = SamModel(UpperCamelCase__ ) hf_model.load_state_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = hf_model.to("""cuda""" ) SCREAMING_SNAKE_CASE__ = """https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = [[[400, 650]]] SCREAMING_SNAKE_CASE__ = [[1]] SCREAMING_SNAKE_CASE__ = processor(images=np.array(UpperCamelCase__ ) , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = hf_model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.5_7_9_8_9_0_2_5_1_1_5_9_6_6_8 SCREAMING_SNAKE_CASE__ = processor( images=np.array(UpperCamelCase__ ) , input_points=UpperCamelCase__ , input_labels=UpperCamelCase__ , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = hf_model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = output.iou_scores.squeeze() assert scores[-1].item() == 0.9_7_1_2_6_0_3_0_9_2_1_9_3_6_0_4 SCREAMING_SNAKE_CASE__ = ((75, 275, 1_725, 850),) SCREAMING_SNAKE_CASE__ = processor(images=np.array(UpperCamelCase__ ) , input_boxes=UpperCamelCase__ , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = hf_model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = output.iou_scores.squeeze() assert scores[-1].item() == 0.8_6_8_6_0_1_5_6_0_5_9_2_6_5_1_4 # Test with 2 points and 1 image. SCREAMING_SNAKE_CASE__ = [[[400, 650], [800, 650]]] SCREAMING_SNAKE_CASE__ = [[1, 1]] SCREAMING_SNAKE_CASE__ = processor( images=np.array(UpperCamelCase__ ) , input_points=UpperCamelCase__ , input_labels=UpperCamelCase__ , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = hf_model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = output.iou_scores.squeeze() assert scores[-1].item() == 0.9_9_3_6_0_4_7_7_9_2_4_3_4_6_9_2 if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() _lowerCamelCase = ['sam_vit_b_01ec64', 'sam_vit_h_4b8939', 'sam_vit_l_0b3195'] parser.add_argument( '--model_name', default='sam_vit_h_4b8939', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) parser.add_argument( '--model_hub_id', default='ybelkada/segment-anything', choices=choices, type=str, help='Path to hf config.json of model to convert', ) _lowerCamelCase = parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
6
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig _lowerCamelCase = logging.get_logger(__name__) # General docstring _lowerCamelCase = 'PoolFormerConfig' # Base docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = [1, 512, 7, 7] # Image classification docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = 'tabby, tabby cat' _lowerCamelCase = [ 'sail/poolformer_s12', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: float = 0.0 , UpperCamelCase__: bool = False ): if drop_prob == 0.0 or not training: return input SCREAMING_SNAKE_CASE__ = 1 - drop_prob SCREAMING_SNAKE_CASE__ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets SCREAMING_SNAKE_CASE__ = keep_prob + torch.rand(UpperCamelCase__ , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize SCREAMING_SNAKE_CASE__ = input.div(UpperCamelCase__ ) * random_tensor return output class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Optional[float] = None ) -> None: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = drop_prob def _snake_case ( self :Any , __A :torch.Tensor ) -> torch.Tensor: """simple docstring""" return drop_path(__A , self.drop_prob , self.training ) def _snake_case ( self :Dict ) -> str: """simple docstring""" return "p={}".format(self.drop_prob ) class UpperCamelCase_ ( nn.Module ): def __init__( self :Dict , __A :Optional[Any] , __A :Dict , __A :List[str] , __A :Optional[Any] , __A :Tuple , __A :Optional[Any]=None ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = patch_size if isinstance(__A , collections.abc.Iterable ) else (patch_size, patch_size) SCREAMING_SNAKE_CASE__ = stride if isinstance(__A , collections.abc.Iterable ) else (stride, stride) SCREAMING_SNAKE_CASE__ = padding if isinstance(__A , collections.abc.Iterable ) else (padding, padding) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , kernel_size=__A , stride=__A , padding=__A ) SCREAMING_SNAKE_CASE__ = norm_layer(__A ) if norm_layer else nn.Identity() def _snake_case ( self :Dict , __A :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.projection(__A ) SCREAMING_SNAKE_CASE__ = self.norm(__A ) return embeddings class UpperCamelCase_ ( nn.GroupNorm ): def __init__( self :Dict , __A :Tuple , **__A :Union[str, Any] ) -> Dict: """simple docstring""" super().__init__(1 , __A , **__A ) class UpperCamelCase_ ( nn.Module ): def __init__( self :List[str] , __A :Optional[int] ) -> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.AvgPoolad(__A , stride=1 , padding=pool_size // 2 , count_include_pad=__A ) def _snake_case ( self :Any , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" return self.pool(__A ) - hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Tuple , __A :Dict , __A :int , __A :Any ) -> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if isinstance(config.hidden_act , __A ): SCREAMING_SNAKE_CASE__ = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE__ = config.hidden_act def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.act_fn(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) return hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :str , __A :List[str] , __A :Tuple , __A :Dict , __A :Union[str, Any] , __A :int ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = PoolFormerPooling(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerOutput(__A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) # Useful for training neural nets SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if drop_path > 0.0 else nn.Identity() SCREAMING_SNAKE_CASE__ = config.use_layer_scale if config.use_layer_scale: SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) def _snake_case ( self :Optional[Any] , __A :Optional[int] ) -> str: """simple docstring""" if self.use_layer_scale: SCREAMING_SNAKE_CASE__ = self.pooling(self.before_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = () SCREAMING_SNAKE_CASE__ = self.output(self.after_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs else: SCREAMING_SNAKE_CASE__ = self.drop_path(self.pooling(self.before_norm(__A ) ) ) # First residual connection SCREAMING_SNAKE_CASE__ = pooling_output + hidden_states SCREAMING_SNAKE_CASE__ = () # Second residual connection inside the PoolFormerOutput block SCREAMING_SNAKE_CASE__ = self.drop_path(self.output(self.after_norm(__A ) ) ) SCREAMING_SNAKE_CASE__ = hidden_states + layer_output SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs class UpperCamelCase_ ( nn.Module ): def __init__( self :Union[str, Any] , __A :List[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = config # stochastic depth decay rule SCREAMING_SNAKE_CASE__ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings SCREAMING_SNAKE_CASE__ = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) # Transformer blocks SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers SCREAMING_SNAKE_CASE__ = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__A ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) def _snake_case ( self :str , __A :Tuple , __A :Dict=False , __A :Tuple=True ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = () if output_hidden_states else None SCREAMING_SNAKE_CASE__ = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = layers # Get patch embeddings from hidden_states SCREAMING_SNAKE_CASE__ = embedding_layer(__A ) # Send the embeddings through the blocks for _, blk in enumerate(__A ): SCREAMING_SNAKE_CASE__ = blk(__A ) SCREAMING_SNAKE_CASE__ = layer_outputs[0] if output_hidden_states: SCREAMING_SNAKE_CASE__ = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__A , hidden_states=__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PoolFormerConfig lowerCamelCase_ = "poolformer" lowerCamelCase_ = "pixel_values" lowerCamelCase_ = True def _snake_case ( self :Optional[Any] , __A :Tuple ) -> Dict: """simple docstring""" if isinstance(__A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _snake_case ( self :str , __A :Optional[Any] , __A :Union[str, Any]=False ) -> Any: """simple docstring""" if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = value _lowerCamelCase = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _lowerCamelCase = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n' @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Any ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config SCREAMING_SNAKE_CASE__ = PoolFormerEncoder(__A ) # Initialize weights and apply final processing self.post_init() def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _snake_case ( self :Dict , __A :Optional[torch.FloatTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) SCREAMING_SNAKE_CASE__ = self.encoder( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__A , hidden_states=encoder_outputs.hidden_states , ) class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :Optional[int] ) -> Tuple: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Linear(config.hidden_size , config.hidden_size ) def _snake_case ( self :List[Any] , __A :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dense(__A ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :str , __A :Union[str, Any] ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config.num_labels SCREAMING_SNAKE_CASE__ = PoolFormerModel(__A ) # Final norm SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head SCREAMING_SNAKE_CASE__ = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _snake_case ( self :int , __A :Optional[torch.FloatTensor] = None , __A :Optional[torch.LongTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ = self.poolformer( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = outputs[0] SCREAMING_SNAKE_CASE__ = self.classifier(self.norm(__A ).mean([-2, -1] ) ) SCREAMING_SNAKE_CASE__ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE__ = """single_label_classification""" else: SCREAMING_SNAKE_CASE__ = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE__ = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE__ = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE__ = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) if not return_dict: SCREAMING_SNAKE_CASE__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__A , logits=__A , hidden_states=outputs.hidden_states )
6
1
import os import numpy import onnx def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = a.name SCREAMING_SNAKE_CASE__ = b.name SCREAMING_SNAKE_CASE__ = """""" SCREAMING_SNAKE_CASE__ = """""" SCREAMING_SNAKE_CASE__ = a == b SCREAMING_SNAKE_CASE__ = name_a SCREAMING_SNAKE_CASE__ = name_b return res def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] ): for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(UpperCamelCase__ , UpperCamelCase__ ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , UpperCamelCase__ , UpperCamelCase__ ) _graph_replace_input_with(node_proto.attribute[1].g , UpperCamelCase__ , UpperCamelCase__ ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): for n in graph_proto.node: _node_replace_input_with(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = list(model.graph.initializer ) SCREAMING_SNAKE_CASE__ = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i SCREAMING_SNAKE_CASE__ = inits[i].name SCREAMING_SNAKE_CASE__ = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = os.path.dirname(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.basename(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = onnx.load(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = list(model.graph.initializer ) SCREAMING_SNAKE_CASE__ = set() SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 for i in range(len(UpperCamelCase__ ) ): if i in dup_set: continue for j in range(i + 1 , len(UpperCamelCase__ ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(UpperCamelCase__ ) dup_set.add(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = inits[j].data_type SCREAMING_SNAKE_CASE__ = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print("""unexpected data type: """ , UpperCamelCase__ ) total_reduced_size += mem_size SCREAMING_SNAKE_CASE__ = inits[i].name SCREAMING_SNAKE_CASE__ = inits[j].name if name_i in dup_map: dup_map[name_i].append(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = [name_j] ind_to_replace.append((j, i) ) print("""total reduced size: """ , total_reduced_size / 1_024 / 1_024 / 1_024 , """GB""" ) SCREAMING_SNAKE_CASE__ = sorted(UpperCamelCase__ ) _remove_dup_initializers_from_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """optimized_""" + model_file_name SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) onnx.save(UpperCamelCase__ , UpperCamelCase__ ) return new_model
6
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device 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 ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Optional[int] , __A :Tuple=13 , __A :Dict=7 , __A :Dict=True , __A :str=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Any=False , __A :Dict=False , __A :Any=False , __A :Tuple=2 , __A :Dict=99 , __A :Optional[Any]=0 , __A :List[str]=32 , __A :Optional[int]=5 , __A :Dict=4 , __A :List[str]=0.1 , __A :Union[str, Any]=0.1 , __A :Tuple=512 , __A :Any=12 , __A :Optional[int]=2 , __A :Union[str, Any]=0.0_2 , __A :Dict=3 , __A :Optional[int]=4 , __A :Any="last" , __A :List[Any]=None , __A :Any=None , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_lengths SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = gelu_activation SCREAMING_SNAKE_CASE__ = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ = causal SCREAMING_SNAKE_CASE__ = asm SCREAMING_SNAKE_CASE__ = n_langs SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_special SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = summary_type SCREAMING_SNAKE_CASE__ = use_proj SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_input_lengths: SCREAMING_SNAKE_CASE__ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , 2 ).float() SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def _snake_case ( self :Tuple , __A :str , __A :int , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[int] , __A :Union[str, Any] , __A :Union[str, Any] , __A :str , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , lengths=__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :str , __A :Any , __A :str , __A :Union[str, Any] , __A :Optional[Any] , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[Any] , __A :Union[str, Any] , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertWithLMHeadModel(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Tuple , __A :Union[str, Any] , __A :Optional[Any] , __A :Dict , __A :Dict , __A :Union[str, Any] , __A :List[str] , __A :Optional[int] , __A :int , __A :str , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnsweringSimple(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :List[str] , __A :Any , __A :int , __A :Tuple , __A :Optional[Any] , __A :Tuple , __A :Optional[int] , __A :str , __A :int , __A :str , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnswering(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , p_mask=__A , ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _snake_case ( self :Optional[int] , __A :str , __A :Optional[int] , __A :Tuple , __A :Dict , __A :List[str] , __A :Tuple , __A :List[str] , __A :Dict , __A :List[str] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self :Optional[Any] , __A :Optional[Any] , __A :Optional[Any] , __A :List[str] , __A :Optional[Any] , __A :int , __A :Tuple , __A :Optional[int] , __A :Union[str, Any] , __A :Dict , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = FlaubertForTokenClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :str , __A :Any , __A :Tuple , __A :List[str] , __A :Tuple , __A :Any , __A :int , __A :Dict , __A :List[str] , __A :Tuple , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = FlaubertForMultipleChoice(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) lowerCamelCase_ = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _snake_case ( self :Any , __A :Optional[int] , __A :Optional[int] , __A :Dict , __A :List[Any] , __A :Tuple ) -> str: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _snake_case ( self :Tuple , __A :List[str] , __A :Optional[int] , __A :Dict=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super()._prepare_for_class(__A , __A , return_labels=__A ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) return inputs_dict def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , emb_dim=37 ) def _snake_case ( self :int ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__A ) def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__A ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__A ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__A ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__A ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__A ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @slow @require_torch_gpu def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = model_class(config=__A ) SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = torch.jit.trace( __A , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__A , os.path.join(__A , """traced_model.pt""" ) ) SCREAMING_SNAKE_CASE__ = torch.jit.load(os.path.join(__A , """traced_model.pt""" ) , map_location=__A ) loaded(inputs_dict["""input_ids"""].to(__A ) , inputs_dict["""attention_mask"""].to(__A ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [[[-2.6_2_5_1, -1.4_2_9_8, -0.0_2_2_7], [-2.8_5_1_0, -1.6_3_8_7, 0.2_2_5_8], [-2.8_1_1_4, -1.1_8_3_2, -0.3_0_6_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=1E-4 ) )
6
1
from __future__ import annotations import math class UpperCamelCase_ : def __init__( self :Tuple , __A :int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = size # approximate the overall size of segment tree with given value SCREAMING_SNAKE_CASE__ = [0 for i in range(0 , 4 * size )] # create array to store lazy update SCREAMING_SNAKE_CASE__ = [0 for i in range(0 , 4 * size )] SCREAMING_SNAKE_CASE__ = [0 for i in range(0 , 4 * size )] # flag for lazy update def _snake_case ( self :Union[str, Any] , __A :int ) -> int: """simple docstring""" return idx * 2 def _snake_case ( self :Dict , __A :int ) -> int: """simple docstring""" return idx * 2 + 1 def _snake_case ( self :Tuple , __A :int , __A :int , __A :int , __A :list[int] ) -> None: """simple docstring""" if left_element == right_element: SCREAMING_SNAKE_CASE__ = a[left_element - 1] else: SCREAMING_SNAKE_CASE__ = (left_element + right_element) // 2 self.build(self.left(__A ) , __A , __A , __A ) self.build(self.right(__A ) , mid + 1 , __A , __A ) SCREAMING_SNAKE_CASE__ = max( self.segment_tree[self.left(__A )] , self.segment_tree[self.right(__A )] ) def _snake_case ( self :Dict , __A :int , __A :int , __A :int , __A :int , __A :int , __A :int ) -> bool: """simple docstring""" if self.flag[idx] is True: SCREAMING_SNAKE_CASE__ = self.lazy[idx] SCREAMING_SNAKE_CASE__ = False if left_element != right_element: SCREAMING_SNAKE_CASE__ = self.lazy[idx] SCREAMING_SNAKE_CASE__ = self.lazy[idx] SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: SCREAMING_SNAKE_CASE__ = val if left_element != right_element: SCREAMING_SNAKE_CASE__ = val SCREAMING_SNAKE_CASE__ = val SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True return True SCREAMING_SNAKE_CASE__ = (left_element + right_element) // 2 self.update(self.left(__A ) , __A , __A , __A , __A , __A ) self.update(self.right(__A ) , mid + 1 , __A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = max( self.segment_tree[self.left(__A )] , self.segment_tree[self.right(__A )] ) return True def _snake_case ( self :Dict , __A :int , __A :int , __A :int , __A :int , __A :int ) -> int | float: """simple docstring""" if self.flag[idx] is True: SCREAMING_SNAKE_CASE__ = self.lazy[idx] SCREAMING_SNAKE_CASE__ = False if left_element != right_element: SCREAMING_SNAKE_CASE__ = self.lazy[idx] SCREAMING_SNAKE_CASE__ = self.lazy[idx] SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] SCREAMING_SNAKE_CASE__ = (left_element + right_element) // 2 SCREAMING_SNAKE_CASE__ = self.query(self.left(__A ) , __A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = self.query(self.right(__A ) , mid + 1 , __A , __A , __A ) return max(__A , __A ) def __str__( self :Optional[Any] ) -> str: """simple docstring""" return str([self.query(1 , 1 , self.size , __A , __A ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _lowerCamelCase = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _lowerCamelCase = 15 _lowerCamelCase = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
6
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple=True ): model.train() SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = F.mse_loss(UpperCamelCase__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[Any]=False ): set_seed(42 ) SCREAMING_SNAKE_CASE__ = RegressionModel() SCREAMING_SNAKE_CASE__ = deepcopy(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) model.to(accelerator.device ) if sched: SCREAMING_SNAKE_CASE__ = AdamW(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = AdamW(params=ddp_model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) # Make a copy of `model` if sched: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): # Test when on a single CPU or GPU that the context manager does nothing SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): # Test on distributed setup that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int=False , UpperCamelCase__: Union[str, Any]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(UpperCamelCase__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple=False , UpperCamelCase__: List[str]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ , UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCamelCase__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n''' SCREAMING_SNAKE_CASE__ = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(UpperCamelCase__ )) if accelerator.num_processes > 1: check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=96 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if iteration < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if batch_num < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(UpperCamelCase__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(UpperCamelCase__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation(UpperCamelCase__ , UpperCamelCase__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" , """2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , """`split_batches=False`, `dispatch_batches=False`**""" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation_with_opt_and_scheduler(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
6
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'vocab_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json' ), }, 'merges_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt' ), }, 'tokenizer_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json', 'roberta-base-openai-detector': ( 'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json' ), 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json' ), }, } _lowerCamelCase = { 'roberta-base': 512, 'roberta-large': 512, 'roberta-large-mnli': 512, 'distilroberta-base': 512, 'roberta-base-openai-detector': 512, 'roberta-large-openai-detector': 512, } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = RobertaTokenizer def __init__( self :List[Any] , __A :Tuple=None , __A :str=None , __A :Tuple=None , __A :Tuple="replace" , __A :List[Any]="<s>" , __A :Union[str, Any]="</s>" , __A :Any="</s>" , __A :Dict="<s>" , __A :Optional[Any]="<unk>" , __A :List[str]="<pad>" , __A :Any="<mask>" , __A :Dict=False , __A :Tuple=True , **__A :Optional[Any] , ) -> Optional[Any]: """simple docstring""" super().__init__( __A , __A , tokenizer_file=__A , errors=__A , bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , unk_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , trim_offsets=__A , **__A , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __A ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = getattr(__A , pre_tok_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = pre_tok_class(**__A ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = """post_processor""" SCREAMING_SNAKE_CASE__ = getattr(self.backend_tokenizer , __A , __A ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE__ = tuple(state["""sep"""] ) if "cls" in state: SCREAMING_SNAKE_CASE__ = tuple(state["""cls"""] ) SCREAMING_SNAKE_CASE__ = False if state.get("""add_prefix_space""" , __A ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = True if state.get("""trim_offsets""" , __A ) != trim_offsets: SCREAMING_SNAKE_CASE__ = trim_offsets SCREAMING_SNAKE_CASE__ = True if changes_to_apply: SCREAMING_SNAKE_CASE__ = getattr(__A , state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = component_class(**__A ) setattr(self.backend_tokenizer , __A , __A ) @property def _snake_case ( self :str ) -> str: """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _snake_case ( self :List[str] , __A :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else value SCREAMING_SNAKE_CASE__ = value def _snake_case ( self :str , *__A :int , **__A :Tuple ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = kwargs.get("""is_split_into_words""" , __A ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__A , **__A ) def _snake_case ( self :Optional[Any] , *__A :List[Any] , **__A :Dict ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = kwargs.get("""is_split_into_words""" , __A ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*__A , **__A ) def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A ) def _snake_case ( self :Dict , __A :Union[str, Any] , __A :Optional[Any]=None ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _snake_case ( self :Optional[int] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
6
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCamelCase_ = "AutoTokenizer" def __init__( self :Optional[int] , __A :Optional[Any] , __A :Dict ) -> Dict: """simple docstring""" super().__init__(__A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor def __call__( self :int , __A :str=None , __A :int=None , __A :Union[str, Any]=None , **__A :str ) -> Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :str , *__A :List[str] , **__A :List[str] ) -> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :List[str] , *__A :Any , **__A :Any ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
6
1
class UpperCamelCase_ : def __init__( self :str , __A :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = n SCREAMING_SNAKE_CASE__ = [None] * self.n SCREAMING_SNAKE_CASE__ = 0 # index of the first element SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 def __len__( self :Dict ) -> int: """simple docstring""" return self.size def _snake_case ( self :Optional[int] ) -> bool: """simple docstring""" return self.size == 0 def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" return False if self.is_empty() else self.array[self.front] def _snake_case ( self :str , __A :Optional[int] ) -> Tuple: """simple docstring""" if self.size >= self.n: raise Exception("""QUEUE IS FULL""" ) SCREAMING_SNAKE_CASE__ = data SCREAMING_SNAKE_CASE__ = (self.rear + 1) % self.n self.size += 1 return self def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" if self.size == 0: raise Exception("""UNDERFLOW""" ) SCREAMING_SNAKE_CASE__ = self.array[self.front] SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = (self.front + 1) % self.n self.size -= 1 return temp
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ = True for i in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = dp[i][j - 1] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE__ = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: SCREAMING_SNAKE_CASE__ = s - 2 * j break return diff
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int] , UpperCamelCase__: list[int] ): # Check if the input is valid if not len(UpperCamelCase__ ) == len(UpperCamelCase__ ) == 3: raise ValueError("""Please enter a valid equation.""" ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError("""Both a & b of two equations can't be zero.""" ) # Extract the coefficients SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = equationa SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = equationa # Calculate the determinants of the matrices SCREAMING_SNAKE_CASE__ = aa * ba - aa * ba SCREAMING_SNAKE_CASE__ = ca * ba - ca * ba SCREAMING_SNAKE_CASE__ = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("""Infinite solutions. (Consistent system)""" ) else: raise ValueError("""No solution. (Inconsistent system)""" ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: SCREAMING_SNAKE_CASE__ = determinant_x / determinant SCREAMING_SNAKE_CASE__ = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
6
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = create_tensor(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = gather(UpperCamelCase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = [state.process_index] SCREAMING_SNAKE_CASE__ = gather_object(UpperCamelCase__ ) assert len(UpperCamelCase__ ) == state.num_processes, f'''{gathered_obj}, {len(UpperCamelCase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = create_tensor(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = broadcast(UpperCamelCase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: SCREAMING_SNAKE_CASE__ = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ = pad_across_processes(UpperCamelCase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # For now runs on only two processes if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ = create_tensor(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = reduce(UpperCamelCase__ , """sum""" ) SCREAMING_SNAKE_CASE__ = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ ), f'''{reduced_tensor} != {truth_tensor}''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): # For now runs on only two processes if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ = create_tensor(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = reduce(UpperCamelCase__ , """mean""" ) SCREAMING_SNAKE_CASE__ = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ ), f'''{reduced_tensor} != {truth_tensor}''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # For xla_spawn (TPUs) main() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = PartialState() state.print(f'''State: {state}''' ) state.print("""testing gather""" ) test_gather(UpperCamelCase__ ) state.print("""testing gather_object""" ) test_gather_object(UpperCamelCase__ ) state.print("""testing broadcast""" ) test_broadcast(UpperCamelCase__ ) state.print("""testing pad_across_processes""" ) test_pad_across_processes(UpperCamelCase__ ) state.print("""testing reduce_sum""" ) test_reduce_sum(UpperCamelCase__ ) state.print("""testing reduce_mean""" ) test_reduce_mean(UpperCamelCase__ ) if __name__ == "__main__": main()
6
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = True def __init__( self :Optional[int] , **__A :str ) -> int: """simple docstring""" super().__init__(**__A ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE__ = kwargs.pop("""encoder""" ) SCREAMING_SNAKE_CASE__ = encoder_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""decoder""" ) SCREAMING_SNAKE_CASE__ = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = True @classmethod def _snake_case ( cls :str , __A :PretrainedConfig , __A :PretrainedConfig , **__A :List[str] ) -> PretrainedConfig: """simple docstring""" logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__A ) def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.encoder.to_dict() SCREAMING_SNAKE_CASE__ = self.decoder.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
6
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowerCamelCase = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': ['CanineTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST', 'CanineForMultipleChoice', 'CanineForQuestionAnswering', 'CanineForSequenceClassification', 'CanineForTokenClassification', 'CanineLayer', 'CanineModel', 'CaninePreTrainedModel', 'load_tf_weights_in_canine', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowerCamelCase_ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"text": Value("string" )} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "text" lowerCamelCase_ = "labels" def _snake_case ( self :Any , __A :Dict ) -> Optional[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] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :str ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
6
1
class UpperCamelCase_ : def __init__( self :Optional[int] , __A :str = "" , __A :bool = False ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = {} # A node will be a leaf if the tree contains its word SCREAMING_SNAKE_CASE__ = is_leaf SCREAMING_SNAKE_CASE__ = prefix def _snake_case ( self :Optional[int] , __A :str ) -> tuple[str, str, str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 0 for q, w in zip(self.prefix , __A ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def _snake_case ( self :Any , __A :list[str] ) -> None: """simple docstring""" for word in words: self.insert(__A ) def _snake_case ( self :Tuple , __A :str ) -> None: """simple docstring""" if self.prefix == word: SCREAMING_SNAKE_CASE__ = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: SCREAMING_SNAKE_CASE__ = RadixNode(prefix=__A , is_leaf=__A ) else: SCREAMING_SNAKE_CASE__ = self.nodes[word[0]] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = incoming_node.match( __A ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(__A ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: SCREAMING_SNAKE_CASE__ = remaining_prefix SCREAMING_SNAKE_CASE__ = self.nodes[matching_string[0]] SCREAMING_SNAKE_CASE__ = RadixNode(__A , __A ) SCREAMING_SNAKE_CASE__ = aux_node if remaining_word == "": SCREAMING_SNAKE_CASE__ = True else: self.nodes[matching_string[0]].insert(__A ) def _snake_case ( self :Optional[int] , __A :str ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.nodes.get(word[0] , __A ) if not incoming_node: return False else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = incoming_node.match( __A ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(__A ) def _snake_case ( self :Optional[Any] , __A :str ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.nodes.get(word[0] , __A ) if not incoming_node: return False else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = incoming_node.match( __A ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(__A ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: SCREAMING_SNAKE_CASE__ = list(self.nodes.values() )[0] SCREAMING_SNAKE_CASE__ = merging_node.is_leaf self.prefix += merging_node.prefix SCREAMING_SNAKE_CASE__ = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: SCREAMING_SNAKE_CASE__ = False # If there is 1 edge, we merge it with its child else: SCREAMING_SNAKE_CASE__ = list(incoming_node.nodes.values() )[0] SCREAMING_SNAKE_CASE__ = merging_node.is_leaf incoming_node.prefix += merging_node.prefix SCREAMING_SNAKE_CASE__ = merging_node.nodes return True def _snake_case ( self :Optional[Any] , __A :int = 0 ) -> None: """simple docstring""" if self.prefix != "": print("""-""" * height , self.prefix , """ (leaf)""" if self.is_leaf else """""" ) for value in self.nodes.values(): value.print_tree(height + 1 ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """banana bananas bandana band apple all beast""".split() SCREAMING_SNAKE_CASE__ = RadixNode() root.insert_many(UpperCamelCase__ ) assert all(root.find(UpperCamelCase__ ) for word in words ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE__ ( ): assert test_trie() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = RadixNode() SCREAMING_SNAKE_CASE__ = """banana bananas bandanas bandana band apple all beast""".split() root.insert_many(UpperCamelCase__ ) print("""Words:""" , UpperCamelCase__ ) print("""Tree:""" ) root.print_tree() if __name__ == "__main__": main()
6
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = model.config SCREAMING_SNAKE_CASE__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) SCREAMING_SNAKE_CASE__ = MBartConfig( is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , ) return encoder_config, decoder_config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if "encoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" ) if "decoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if name.startswith("""encoder""" ): if "layers" in name: SCREAMING_SNAKE_CASE__ = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "mask" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight""" if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias""" return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_split[3] ) SCREAMING_SNAKE_CASE__ = int(key_split[5] ) SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE__ = val[:dim, :] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ = val[-dim:, :] else: SCREAMING_SNAKE_CASE__ = val[:dim] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: SCREAMING_SNAKE_CASE__ = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): # load original model SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval() # load HuggingFace model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = original_model.state_dict() SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify results on scanned document SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" ) SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" SCREAMING_SNAKE_CASE__ = """When is the coffee break?""" SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>""" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: SCREAMING_SNAKE_CASE__ = """<s_cord>""" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": SCREAMING_SNAKE_CASE__ = """s_cord-v2>""" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>""" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt SCREAMING_SNAKE_CASE__ = """hello world""" else: raise ValueError("""Model name not supported""" ) SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[ """input_ids""" ] SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) # verify encoder hidden states SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) # verify decoder hidden states SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, 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 and processor to the 🤗 hub.', ) _lowerCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
6
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "facebook/bart-large-mnli" lowerCamelCase_ = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) lowerCamelCase_ = "text_classifier" lowerCamelCase_ = AutoTokenizer lowerCamelCase_ = AutoModelForSequenceClassification lowerCamelCase_ = ["text", ["text"]] lowerCamelCase_ = ["text"] def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = self.model.config SCREAMING_SNAKE_CASE__ = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): SCREAMING_SNAKE_CASE__ = int(__A ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def _snake_case ( self :Optional[Any] , __A :Optional[Any] , __A :Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = labels return self.pre_processor( [text] * len(__A ) , [f'''This example is {label}''' for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _snake_case ( self :str , __A :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = outputs.logits SCREAMING_SNAKE_CASE__ = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
6
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_dpmpp_2m""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=7.5 , num_inference_steps=15 , output_type="""np""" , use_karras_sigmas=__A , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
6
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json', } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "open-llama" def __init__( self :Union[str, Any] , __A :Tuple=10_0000 , __A :Dict=4096 , __A :int=1_1008 , __A :Optional[int]=32 , __A :Optional[Any]=32 , __A :Dict="silu" , __A :List[str]=2048 , __A :Dict=0.0_2 , __A :Dict=1E-6 , __A :Union[str, Any]=True , __A :Any=0 , __A :List[Any]=1 , __A :Any=2 , __A :Optional[Any]=False , __A :Tuple=True , __A :Optional[int]=0.1 , __A :Tuple=0.1 , __A :str=True , __A :Union[str, Any]=True , __A :Any=None , **__A :Any , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = rms_norm_eps SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = kwargs.pop( """use_memorry_efficient_attention""" , __A ) SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_dropout_prob SCREAMING_SNAKE_CASE__ = use_stable_embedding SCREAMING_SNAKE_CASE__ = shared_input_output_embedding SCREAMING_SNAKE_CASE__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , tie_word_embeddings=__A , **__A , ) def _snake_case ( self :Optional[int] ) -> int: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __A ) or len(self.rope_scaling ) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ f'''got {self.rope_scaling}''' ) SCREAMING_SNAKE_CASE__ = self.rope_scaling.get("""type""" , __A ) SCREAMING_SNAKE_CASE__ = self.rope_scaling.get("""factor""" , __A ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__A , __A ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE__ = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE__ = n return int(UpperCamelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
6
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "CLIPImageProcessor" lowerCamelCase_ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self :List[Any] , __A :Tuple=None , __A :Dict=None , **__A :Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :Any , __A :str=None , __A :List[Any]=None , __A :Union[str, Any]=None , **__A :List[Any] ) -> List[str]: """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :Union[str, Any] , *__A :Optional[int] , **__A :Any ) -> str: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Optional[Any] , *__A :str , **__A :Tuple ) -> List[Any]: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _snake_case ( self :Dict ) -> int: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class @property def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __A , ) return self.image_processor
6
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) )
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int ): if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) SCREAMING_SNAKE_CASE__ = str(bin(UpperCamelCase__ ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE__ = str(bin(UpperCamelCase__ ) )[2:] SCREAMING_SNAKE_CASE__ = max(len(UpperCamelCase__ ) , len(UpperCamelCase__ ) ) return "0b" + "".join( str(int("""1""" in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(UpperCamelCase__ ) , b_binary.zfill(UpperCamelCase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
6
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""": """Friday""", """6""": """Saturday""", } SCREAMING_SNAKE_CASE__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(UpperCamelCase__ ) < 11: raise ValueError("""Must be 10 characters long""" ) # Get month SCREAMING_SNAKE_CASE__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("""Month must be between 1 - 12""" ) SCREAMING_SNAKE_CASE__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get day SCREAMING_SNAKE_CASE__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("""Date must be between 1 - 31""" ) # Get second separator SCREAMING_SNAKE_CASE__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get year SCREAMING_SNAKE_CASE__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8_500: raise ValueError( """Year out of range. There has to be some sort of limit...right?""" ) # Get datetime obj for validation SCREAMING_SNAKE_CASE__ = datetime.date(int(UpperCamelCase__ ) , int(UpperCamelCase__ ) , int(UpperCamelCase__ ) ) # Start math if m <= 2: SCREAMING_SNAKE_CASE__ = y - 1 SCREAMING_SNAKE_CASE__ = m + 12 # maths var SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[:2] ) SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[2:] ) SCREAMING_SNAKE_CASE__ = int(2.6 * m - 5.3_9 ) SCREAMING_SNAKE_CASE__ = int(c / 4 ) SCREAMING_SNAKE_CASE__ = int(k / 4 ) SCREAMING_SNAKE_CASE__ = int(d + k ) SCREAMING_SNAKE_CASE__ = int(t + u + v + x ) SCREAMING_SNAKE_CASE__ = int(z - (2 * c) ) SCREAMING_SNAKE_CASE__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" ) # Response SCREAMING_SNAKE_CASE__ = f'''Your date {date_input}, is a {days[str(UpperCamelCase__ )]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) _lowerCamelCase = parser.parse_args() zeller(args.date_input)
6
1
import functools from typing import Any def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: list[str] ): # Validation if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or len(UpperCamelCase__ ) == 0: raise ValueError("""the string should be not empty string""" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not all( isinstance(UpperCamelCase__ , UpperCamelCase__ ) and len(UpperCamelCase__ ) > 0 for item in words ): raise ValueError("""the words should be a list of non-empty strings""" ) # Build trie SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = """WORD_KEEPER""" for word in words: SCREAMING_SNAKE_CASE__ = trie for c in word: if c not in trie_node: SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = trie_node[c] SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) # Dynamic programming method @functools.cache def is_breakable(UpperCamelCase__: int ) -> bool: if index == len_string: return True SCREAMING_SNAKE_CASE__ = trie for i in range(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = trie_node.get(string[i] , UpperCamelCase__ ) if trie_node is None: return False if trie_node.get(UpperCamelCase__ , UpperCamelCase__ ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
6
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30522, type=int) _lowerCamelCase = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: _lowerCamelCase = pickle.load(fp) logger.info('Counting occurrences for MLM.') _lowerCamelCase = Counter() for tk_ids in data: counter.update(tk_ids) _lowerCamelCase = [0] * args.vocab_size for k, v in counter.items(): _lowerCamelCase = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
6
1
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple=True ): model.train() SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = F.mse_loss(UpperCamelCase__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[Any]=False ): set_seed(42 ) SCREAMING_SNAKE_CASE__ = RegressionModel() SCREAMING_SNAKE_CASE__ = deepcopy(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) model.to(accelerator.device ) if sched: SCREAMING_SNAKE_CASE__ = AdamW(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = AdamW(params=ddp_model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) # Make a copy of `model` if sched: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): # Test when on a single CPU or GPU that the context manager does nothing SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): # Test on distributed setup that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int=False , UpperCamelCase__: Union[str, Any]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(UpperCamelCase__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple=False , UpperCamelCase__: List[str]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ , UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCamelCase__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n''' SCREAMING_SNAKE_CASE__ = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(UpperCamelCase__ )) if accelerator.num_processes > 1: check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=96 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if iteration < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if batch_num < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(UpperCamelCase__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(UpperCamelCase__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation(UpperCamelCase__ , UpperCamelCase__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" , """2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , """`split_batches=False`, `dispatch_batches=False`**""" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation_with_opt_and_scheduler(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
6
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
1
from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class UpperCamelCase_ ( yaml.SafeLoader ): def _snake_case ( self :List[str] , __A :List[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.constructed_objects[key_node] for key_node, _ in node.value] SCREAMING_SNAKE_CASE__ = [tuple(__A ) if isinstance(__A , __A ) else key for key in keys] SCREAMING_SNAKE_CASE__ = Counter(__A ) SCREAMING_SNAKE_CASE__ = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}''' ) def _snake_case ( self :Optional[int] , __A :List[Any] , __A :Union[str, Any]=False ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = super().construct_mapping(__A , deep=__A ) self._check_no_duplicates_on_constructed_node(__A ) return mapping def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: SCREAMING_SNAKE_CASE__ = full_content[1:].index("""---""" ) + 1 SCREAMING_SNAKE_CASE__ = """\n""".join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # class attributes lowerCamelCase_ = {"train_eval_index"} # train-eval-index in the YAML metadata @classmethod def _snake_case ( cls :int , __A :Path ) -> "DatasetMetadata": """simple docstring""" with open(__A , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(__A ) else: return cls() def _snake_case ( self :int , __A :Path ) -> str: """simple docstring""" if path.exists(): with open(__A , encoding="""utf-8""" ) as readme_file: SCREAMING_SNAKE_CASE__ = readme_file.read() else: SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = self._to_readme(__A ) with open(__A , """w""" , encoding="""utf-8""" ) as readme_file: readme_file.write(__A ) def _snake_case ( self :int , __A :Optional[str] = None ) -> str: """simple docstring""" if readme_content is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = _split_yaml_from_readme(__A ) SCREAMING_SNAKE_CASE__ = """---\n""" + self.to_yaml_string() + """---\n""" + content else: SCREAMING_SNAKE_CASE__ = """---\n""" + self.to_yaml_string() + """---\n""" return full_content @classmethod def _snake_case ( cls :Tuple , __A :str ) -> "DatasetMetadata": """simple docstring""" SCREAMING_SNAKE_CASE__ = yaml.load(__A , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields SCREAMING_SNAKE_CASE__ = { (key.replace("""-""" , """_""" ) if key.replace("""-""" , """_""" ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**__A ) def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" return yaml.safe_dump( { (key.replace("""_""" , """-""" ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=__A , allow_unicode=__A , encoding="""utf-8""" , ).decode("""utf-8""" ) _lowerCamelCase = { 'image-classification': [], 'translation': [], 'image-segmentation': [], 'fill-mask': [], 'automatic-speech-recognition': [], 'token-classification': [], 'sentence-similarity': [], 'audio-classification': [], 'question-answering': [], 'summarization': [], 'zero-shot-classification': [], 'table-to-text': [], 'feature-extraction': [], 'other': [], 'multiple-choice': [], 'text-classification': [], 'text-to-image': [], 'text2text-generation': [], 'zero-shot-image-classification': [], 'tabular-classification': [], 'tabular-regression': [], 'image-to-image': [], 'tabular-to-text': [], 'unconditional-image-generation': [], 'text-retrieval': [], 'text-to-speech': [], 'object-detection': [], 'audio-to-audio': [], 'text-generation': [], 'conversational': [], 'table-question-answering': [], 'visual-question-answering': [], 'image-to-text': [], 'reinforcement-learning': [], 'voice-activity-detection': [], 'time-series-forecasting': [], 'document-question-answering': [], } if __name__ == "__main__": from argparse import ArgumentParser _lowerCamelCase = ArgumentParser(usage='Validate the yaml metadata block of a README.md file.') ap.add_argument('readme_filepath') _lowerCamelCase = ap.parse_args() _lowerCamelCase = Path(args.readme_filepath) _lowerCamelCase = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
6
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "OwlViTImageProcessor" lowerCamelCase_ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self :Optional[Any] , __A :int=None , __A :Optional[int]=None , **__A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :str , __A :Dict=None , __A :List[str]=None , __A :str=None , __A :Optional[int]="max_length" , __A :Tuple="np" , **__A :int ) -> Tuple: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(__A , __A ) or (isinstance(__A , __A ) and not isinstance(text[0] , __A )): SCREAMING_SNAKE_CASE__ = [self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )] elif isinstance(__A , __A ) and isinstance(text[0] , __A ): SCREAMING_SNAKE_CASE__ = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ = max([len(__A ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(__A ) != max_num_queries: SCREAMING_SNAKE_CASE__ = t + [""" """] * (max_num_queries - len(__A )) SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , padding=__A , return_tensors=__A , **__A ) encodings.append(__A ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = input_ids SCREAMING_SNAKE_CASE__ = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = self.image_processor( __A , return_tensors=__A , **__A ).pixel_values SCREAMING_SNAKE_CASE__ = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Dict , **__A :Dict ) -> Optional[int]: """simple docstring""" return self.image_processor.post_process(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Dict , **__A :List[str] ) -> Optional[Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*__A , **__A ) def _snake_case ( self :str , *__A :List[str] , **__A :Union[str, Any] ) -> Any: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*__A , **__A ) def _snake_case ( self :Dict , *__A :List[str] , **__A :List[str] ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Dict , *__A :Dict , **__A :List[str] ) -> str: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class @property def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __A , ) return self.image_processor
6
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "distilbert" lowerCamelCase_ = { "hidden_size": "dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", } def __init__( self :Optional[int] , __A :Optional[Any]=3_0522 , __A :Tuple=512 , __A :Dict=False , __A :Any=6 , __A :int=12 , __A :Dict=768 , __A :Any=4 * 768 , __A :Dict=0.1 , __A :str=0.1 , __A :Optional[Any]="gelu" , __A :int=0.0_2 , __A :Optional[Any]=0.1 , __A :List[str]=0.2 , __A :Optional[int]=0 , **__A :int , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = sinusoidal_pos_embds SCREAMING_SNAKE_CASE__ = n_layers SCREAMING_SNAKE_CASE__ = n_heads SCREAMING_SNAKE_CASE__ = dim SCREAMING_SNAKE_CASE__ = hidden_dim SCREAMING_SNAKE_CASE__ = dropout SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = activation SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = qa_dropout SCREAMING_SNAKE_CASE__ = seq_classif_dropout super().__init__(**__A , pad_token_id=__A ) class UpperCamelCase_ ( UpperCamelCase__ ): @property def _snake_case ( self :Any ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
6
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self :Union[str, Any] , __A :int = 3 , __A :int = 3 , __A :Tuple[str] = ("DownEncoderBlock2D",) , __A :Tuple[str] = ("UpDecoderBlock2D",) , __A :Tuple[int] = (64,) , __A :int = 1 , __A :str = "silu" , __A :int = 3 , __A :int = 32 , __A :int = 256 , __A :int = 32 , __A :Optional[int] = None , __A :float = 0.1_8_2_1_5 , __A :str = "group" , ) -> Any: """simple docstring""" super().__init__() # pass init params to Encoder SCREAMING_SNAKE_CASE__ = Encoder( in_channels=__A , out_channels=__A , down_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , double_z=__A , ) SCREAMING_SNAKE_CASE__ = vq_embed_dim if vq_embed_dim is not None else latent_channels SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = VectorQuantizer(__A , __A , beta=0.2_5 , remap=__A , sane_index_shape=__A ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) # pass init params to Decoder SCREAMING_SNAKE_CASE__ = Decoder( in_channels=__A , out_channels=__A , up_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , norm_type=__A , ) @apply_forward_hook def _snake_case ( self :Union[str, Any] , __A :torch.FloatTensor , __A :bool = True ) -> VQEncoderOutput: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.encoder(__A ) SCREAMING_SNAKE_CASE__ = self.quant_conv(__A ) if not return_dict: return (h,) return VQEncoderOutput(latents=__A ) @apply_forward_hook def _snake_case ( self :Tuple , __A :torch.FloatTensor , __A :bool = False , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" if not force_not_quantize: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = h SCREAMING_SNAKE_CASE__ = self.post_quant_conv(__A ) SCREAMING_SNAKE_CASE__ = self.decoder(__A , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=__A ) def _snake_case ( self :int , __A :torch.FloatTensor , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample SCREAMING_SNAKE_CASE__ = self.encode(__A ).latents SCREAMING_SNAKE_CASE__ = self.decode(__A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__A )
6
1
from __future__ import annotations from typing import Any def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[Any] ): create_state_space_tree(UpperCamelCase__ , [] , 0 ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[Any] , UpperCamelCase__: list[Any] , UpperCamelCase__: int ): if index == len(UpperCamelCase__ ): print(UpperCamelCase__ ) return create_state_space_tree(UpperCamelCase__ , UpperCamelCase__ , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(UpperCamelCase__ , UpperCamelCase__ , index + 1 ) current_subsequence.pop() if __name__ == "__main__": _lowerCamelCase = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(['A', 'B', 'C']) generate_all_subsequences(seq)
6
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = jnp.floataa lowerCamelCase_ = True def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = nn.Dense(5 , dtype=self.dtype ) def __call__( self :List[Any] , *__A :int , **__A :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super().__call__(*__A , **__A ) SCREAMING_SNAKE_CASE__ = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = FlaxBigBirdForNaturalQuestionsModule def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): def cross_entropy(UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=None ): SCREAMING_SNAKE_CASE__ = logits.shape[-1] SCREAMING_SNAKE_CASE__ = (labels[..., None] == jnp.arange(UpperCamelCase__ )[None]).astype("""f4""" ) SCREAMING_SNAKE_CASE__ = jax.nn.log_softmax(UpperCamelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE__ = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: SCREAMING_SNAKE_CASE__ = reduction(UpperCamelCase__ ) return loss SCREAMING_SNAKE_CASE__ = partial(UpperCamelCase__ , reduction=jnp.mean ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class UpperCamelCase_ : lowerCamelCase_ = "google/bigbird-roberta-base" lowerCamelCase_ = 30_00 lowerCamelCase_ = 1_05_00 lowerCamelCase_ = 1_28 lowerCamelCase_ = 3 lowerCamelCase_ = 1 lowerCamelCase_ = 5 # tx_args lowerCamelCase_ = 3e-5 lowerCamelCase_ = 0.0 lowerCamelCase_ = 2_00_00 lowerCamelCase_ = 0.0095 lowerCamelCase_ = "bigbird-roberta-natural-questions" lowerCamelCase_ = "training-expt" lowerCamelCase_ = "data/nq-training.jsonl" lowerCamelCase_ = "data/nq-validation.jsonl" def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(self.base_dir , self.save_dir ) SCREAMING_SNAKE_CASE__ = self.batch_size_per_device * jax.device_count() @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 40_96 # no dynamic padding on TPUs def __call__( self :Optional[Any] , __A :Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.collate_fn(__A ) SCREAMING_SNAKE_CASE__ = jax.tree_util.tree_map(__A , __A ) return batch def _snake_case ( self :List[Any] , __A :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.fetch_inputs(features["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = { """input_ids""": jnp.array(__A , dtype=jnp.intaa ), """attention_mask""": jnp.array(__A , dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ), } return batch def _snake_case ( self :Tuple , __A :list ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self._fetch_inputs(__A ) for ids in input_ids] return zip(*__A ) def _snake_case ( self :List[str] , __A :list ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [1 for _ in range(len(__A ) )] while len(__A ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=None ): if seed is not None: SCREAMING_SNAKE_CASE__ = dataset.shuffle(seed=UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) // batch_size ): SCREAMING_SNAKE_CASE__ = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase__ ) @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] , **UpperCamelCase__: Optional[int] ): def loss_fn(UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=UpperCamelCase__ , dropout_rng=UpperCamelCase__ , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs return state.loss_fn( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = jax.random.split(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.value_and_grad(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = grad_fn(state.params ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean(UpperCamelCase__ , """batch""" ) SCREAMING_SNAKE_CASE__ = state.apply_gradients(grads=UpperCamelCase__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , **UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=state.params , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs SCREAMING_SNAKE_CASE__ = state.loss_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class UpperCamelCase_ ( train_state.TrainState ): lowerCamelCase_ = struct.field(pytree_node=UpperCamelCase__ ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None def _snake_case ( self :List[Any] , __A :str , __A :str , __A :str , __A :Tuple=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = model.params SCREAMING_SNAKE_CASE__ = TrainState.create( apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , ) if ckpt_dir is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = restore_checkpoint(__A , __A ) SCREAMING_SNAKE_CASE__ = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = build_tx(**__A ) SCREAMING_SNAKE_CASE__ = train_state.TrainState( step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = data_collator SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = jax_utils.replicate(__A ) return state def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :int , __A :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.args SCREAMING_SNAKE_CASE__ = len(__A ) // args.batch_size SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ = jax.random.split(__A , jax.device_count() ) for epoch in range(args.max_epochs ): SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , args.batch_size , seed=__A ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc=f'''Running EPOCH-{epoch}''' ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.train_step_fn(__A , __A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(state.step ) SCREAMING_SNAKE_CASE__ = running_loss.item() / i SCREAMING_SNAKE_CASE__ = self.scheduler_fn(state_step - 1 ) SCREAMING_SNAKE_CASE__ = self.evaluate(__A , __A ) SCREAMING_SNAKE_CASE__ = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(__A ) ) self.logger.log(__A , commit=__A ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__A ) def _snake_case ( self :List[str] , __A :Dict , __A :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , self.args.batch_size ) SCREAMING_SNAKE_CASE__ = len(__A ) // self.args.batch_size SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc="""Evaluating ... """ ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ = self.val_step_fn(__A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _snake_case ( self :List[Any] , __A :Any , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(__A ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=""" ... """ ) self.model_save_fn(__A , params=state.params ) with open(os.path.join(__A , """opt_state.msgpack""" ) , """wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__A , """args.joblib""" ) ) joblib.dump(self.data_collator , os.path.join(__A , """data_collator.joblib""" ) ) with open(os.path.join(__A , """training_state.json""" ) , """w""" ) as f: json.dump({"""step""": state.step.item()} , __A ) print("""DONE""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=""" ... """ ) with open(os.path.join(UpperCamelCase__ , """flax_model.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase__ , """opt_state.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.opt_state , f.read() ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """args.joblib""" ) ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """data_collator.joblib""" ) ) with open(os.path.join(UpperCamelCase__ , """training_state.json""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = num_train_steps - warmup_steps SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=UpperCamelCase__ , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=1e-7 , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): def weight_decay_mask(UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = traverse_util.flatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = scheduler_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.adamw(learning_rate=UpperCamelCase__ , weight_decay=UpperCamelCase__ , mask=UpperCamelCase__ ) return tx, lr
6
1
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCamelCase = 1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py _lowerCamelCase = 0 _lowerCamelCase = 0XE0_00 _lowerCamelCase = 0XE0_01 _lowerCamelCase = 0XE0_02 _lowerCamelCase = 0XE0_03 _lowerCamelCase = 0XE0_04 # Maps special codepoints to human-readable names. _lowerCamelCase = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. _lowerCamelCase = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self :str , __A :str=chr(__A ) , __A :str=chr(__A ) , __A :Dict=chr(__A ) , __A :str=chr(__A ) , __A :Union[str, Any]=chr(__A ) , __A :str=chr(__A ) , __A :int=False , __A :int=2048 , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , model_max_length=__A , **__A , ) # Creates a mapping for looking up the IDs of special symbols. SCREAMING_SNAKE_CASE__ = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): SCREAMING_SNAKE_CASE__ = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. SCREAMING_SNAKE_CASE__ = { codepoint: name for name, codepoint in self._special_codepoints.items() } SCREAMING_SNAKE_CASE__ = UNICODE_VOCAB_SIZE SCREAMING_SNAKE_CASE__ = len(self._special_codepoints ) @property def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" return self._unicode_vocab_size def _snake_case ( self :Tuple , __A :str ) -> List[str]: """simple docstring""" return list(__A ) def _snake_case ( self :Optional[Any] , __A :str ) -> int: """simple docstring""" try: return ord(__A ) except TypeError: raise ValueError(f'''invalid token: \'{token}\'''' ) def _snake_case ( self :str , __A :int ) -> str: """simple docstring""" try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(__A ) except TypeError: raise ValueError(f'''invalid id: {index}''' ) def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Any: """simple docstring""" return "".join(__A ) def _snake_case ( self :Optional[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] + ([0] * len(__A )) + [1] if token_ids_a is not None: result += ([0] * len(__A )) + [1] return result def _snake_case ( self :List[str] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Any: """simple docstring""" return ()
6
from torch import nn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported activation function: {act_fn}''' )
6
1
import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = RobertaPreLayerNormConfig.from_pretrained( UpperCamelCase__ , architectures=["""RobertaPreLayerNormForMaskedLM"""] ) # convert state_dict SCREAMING_SNAKE_CASE__ = torch.load(hf_hub_download(repo_id=UpperCamelCase__ , filename="""pytorch_model.bin""" ) ) SCREAMING_SNAKE_CASE__ = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith("""roberta.""" ): SCREAMING_SNAKE_CASE__ = """roberta_prelayernorm.""" + tensor_key[len("""roberta.""" ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith(""".self.LayerNorm.weight""" ) or tensor_key.endswith(""".self.LayerNorm.bias""" ): continue SCREAMING_SNAKE_CASE__ = tensor_value SCREAMING_SNAKE_CASE__ = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=UpperCamelCase__ , config=UpperCamelCase__ , state_dict=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) # convert tokenizer SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(UpperCamelCase__ ) tokenizer.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint-repo', default=None, type=str, required=True, help='Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
6
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = SwinConfig.from_pretrained( """microsoft/swin-tiny-patch4-window7-224""" , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) SCREAMING_SNAKE_CASE__ = MaskFormerConfig(backbone_config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" if "ade20k-full" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 847 SCREAMING_SNAKE_CASE__ = """maskformer-ade20k-full-id2label.json""" elif "ade" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 150 SCREAMING_SNAKE_CASE__ = """ade20k-id2label.json""" elif "coco-stuff" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 171 SCREAMING_SNAKE_CASE__ = """maskformer-coco-stuff-id2label.json""" elif "coco" in model_name: # TODO SCREAMING_SNAKE_CASE__ = 133 SCREAMING_SNAKE_CASE__ = """coco-panoptic-id2label.json""" elif "cityscapes" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 19 SCREAMING_SNAKE_CASE__ = """cityscapes-id2label.json""" elif "vistas" in model_name: # this should be ok SCREAMING_SNAKE_CASE__ = 65 SCREAMING_SNAKE_CASE__ = """mapillary-vistas-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [] # stem # fmt: off rename_keys.append(("""backbone.patch_embed.proj.weight""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.proj.bias""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """model.pixel_level_module.encoder.model.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """model.pixel_level_module.encoder.model.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.norm2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.layers.{i}.downsample.reduction.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.weight''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.layers.{i}.downsample.norm.bias''', f'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''') ) # FPN rename_keys.append(("""sem_seg_head.layer_4.weight""", """model.pixel_level_module.decoder.fpn.stem.0.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.weight""", """model.pixel_level_module.decoder.fpn.stem.1.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.bias""", """model.pixel_level_module.decoder.fpn.stem.1.bias""") ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((f'''sem_seg_head.adapter_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''') ) rename_keys.append((f'''sem_seg_head.adapter_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.weight''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''') ) rename_keys.append((f'''sem_seg_head.layer_{source_index}.norm.bias''', f'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''') ) rename_keys.append(("""sem_seg_head.mask_features.weight""", """model.pixel_level_module.decoder.mask_projection.weight""") ) rename_keys.append(("""sem_seg_head.mask_features.bias""", """model.pixel_level_module.decoder.mask_projection.bias""") ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''') ) # cross-attention out projection rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''') ) # MLP 1 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc1.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc1.bias''') ) # MLP 2 rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', f'''model.transformer_module.decoder.layers.{idx}.fc2.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', f'''model.transformer_module.decoder.layers.{idx}.fc2.bias''') ) # layernorm 1 (self-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', f'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', f'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''') ) # layernorm 3 (final layernorm) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', f'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''') ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.weight""", """model.transformer_module.decoder.layernorm.weight""") ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.bias""", """model.transformer_module.decoder.layernorm.bias""") ) # heads on top rename_keys.append(("""sem_seg_head.predictor.query_embed.weight""", """model.transformer_module.queries_embedder.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.weight""", """model.transformer_module.input_projection.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.bias""", """model.transformer_module.input_projection.bias""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.weight""", """class_predictor.weight""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.bias""", """class_predictor.bias""") ) for i in range(3 ): rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', f'''mask_embedder.{i}.0.weight''') ) rename_keys.append((f'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', f'''mask_embedder.{i}.0.bias''') ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE__ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[: dim] SCREAMING_SNAKE_CASE__ = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-dim :] # fmt: on def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): # fmt: off SCREAMING_SNAKE_CASE__ = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[:config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[hidden_size : hidden_size * 2, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[hidden_size : hidden_size * 2] SCREAMING_SNAKE_CASE__ = in_proj_weight[-hidden_size :, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[-hidden_size :] # fmt: on def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: bool = False ): SCREAMING_SNAKE_CASE__ = get_maskformer_config(UpperCamelCase__ ) # load original state_dict with open(UpperCamelCase__ , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = data["""model"""] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys SCREAMING_SNAKE_CASE__ = create_rename_keys(UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) read_in_swin_q_k_v(UpperCamelCase__ , config.backbone_config ) read_in_decoder_q_k_v(UpperCamelCase__ , UpperCamelCase__ ) # update to torch tensors for key, value in state_dict.items(): SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) # load 🤗 model SCREAMING_SNAKE_CASE__ = MaskFormerForInstanceSegmentation(UpperCamelCase__ ) model.eval() for name, param in model.named_parameters(): print(UpperCamelCase__ , param.shape ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(UpperCamelCase__ ) == 0, f'''Unexpected keys: {unexpected_keys}''' # verify results SCREAMING_SNAKE_CASE__ = prepare_img() if "vistas" in model_name: SCREAMING_SNAKE_CASE__ = 65 elif "cityscapes" in model_name: SCREAMING_SNAKE_CASE__ = 65_535 else: SCREAMING_SNAKE_CASE__ = 255 SCREAMING_SNAKE_CASE__ = True if """ade""" in model_name else False SCREAMING_SNAKE_CASE__ = MaskFormerImageProcessor(ignore_index=UpperCamelCase__ , reduce_labels=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(UpperCamelCase__ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = model(**UpperCamelCase__ ) print("""Logits:""" , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": SCREAMING_SNAKE_CASE__ = torch.tensor( [[3.6_3_5_3, -4.4_7_7_0, -2.6_0_6_5], [0.5_0_8_1, -4.2_3_9_4, -3.5_3_4_3], [2.1_9_0_9, -5.0_3_5_3, -1.9_3_2_3]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and image processor to {pytorch_dump_folder_path}''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: print("""Pushing model and image processor to the hub...""" ) model.push_to_hub(f'''nielsr/{model_name}''' ) image_processor.push_to_hub(f'''nielsr/{model_name}''' ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='maskformer-swin-tiny-ade', type=str, help=('Name of the MaskFormer model you\'d like to convert',), ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl', type=str, help='Path to the original state dict (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, 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.' ) _lowerCamelCase = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
6
1
import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class UpperCamelCase_ : def __init__( self :int , __A :Optional[Any] , __A :Any=13 , __A :Optional[int]=7 , __A :str=True , __A :Tuple=True , __A :Union[str, Any]=True , __A :int=True , __A :Any=99 , __A :Union[str, Any]=64 , __A :int=32 , __A :Tuple=5 , __A :int=4 , __A :Tuple=37 , __A :Optional[Any]="gelu" , __A :Union[str, Any]=0.1 , __A :Any=0.1 , __A :str=512 , __A :Tuple=16 , __A :Optional[Any]=2 , __A :Tuple=0.0_2 , __A :int=3 , __A :Union[str, Any]=4 , __A :List[Any]=None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = embedding_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self :int ) -> Union[str, Any]: """simple docstring""" return MegatronBertConfig( 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 , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__A , initializer_range=self.initializer_range , ) def _snake_case ( self :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Union[str, Any] , __A :int , __A :str , __A :List[Any] , __A :List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MegatronBertModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , token_type_ids=__A ) SCREAMING_SNAKE_CASE__ = model(__A , token_type_ids=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _snake_case ( self :List[Any] , __A :List[str] , __A :Optional[Any] , __A :Optional[int] , __A :List[str] , __A :List[Any] , __A :int , __A :Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = MegatronBertForMaskedLM(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :List[Any] , __A :Any , __A :Tuple , __A :str , __A :str , __A :List[str] , __A :Union[str, Any] , __A :Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = MegatronBertForCausalLM(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Tuple , __A :int , __A :Optional[int] , __A :Union[str, Any] , __A :Union[str, Any] , __A :int , __A :Union[str, Any] , __A :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = MegatronBertForNextSentencePrediction(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def _snake_case ( self :Union[str, Any] , __A :str , __A :Any , __A :Union[str, Any] , __A :List[Any] , __A :Any , __A :str , __A :Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MegatronBertForPreTraining(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , next_sentence_label=__A , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def _snake_case ( self :Optional[Any] , __A :int , __A :Optional[Any] , __A :List[Any] , __A :Tuple , __A :Any , __A :Union[str, Any] , __A :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MegatronBertForQuestionAnswering(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , start_positions=__A , end_positions=__A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :str , __A :int , __A :List[Any] , __A :Tuple , __A :Optional[Any] , __A :Optional[int] , __A :Dict , __A :Optional[int] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = MegatronBertForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :Optional[Any] , __A :List[Any] , __A :List[Any] , __A :Any , __A :Tuple , __A :Any , __A :Optional[int] , __A :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = MegatronBertForTokenClassification(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :Optional[Any] , __A :int , __A :List[Any] , __A :List[str] , __A :Any , __A :List[Any] , __A :Any , __A :Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = MegatronBertForMultipleChoice(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) lowerCamelCase_ = ( { "feature-extraction": MegatronBertModel, "fill-mask": MegatronBertForMaskedLM, "question-answering": MegatronBertForQuestionAnswering, "text-classification": MegatronBertForSequenceClassification, "text-generation": MegatronBertForCausalLM, "token-classification": MegatronBertForTokenClassification, "zero-shot": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase_ = True # test_resize_embeddings = False lowerCamelCase_ = False def _snake_case ( self :int , __A :Tuple , __A :List[str] , __A :int=False ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = super()._prepare_for_class(__A , __A , return_labels=__A ) if return_labels: if model_class in get_values(__A ): SCREAMING_SNAKE_CASE__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__A ) SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) return inputs_dict def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MegatronBertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , hidden_size=37 ) def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*__A ) def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__A ) def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__A ) def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__A ) def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*__A ) def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*__A ) def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__A ) def _snake_case ( self :Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*__A ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): return torch.tensor( UpperCamelCase__ , dtype=torch.long , device=UpperCamelCase__ , ) _lowerCamelCase = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( unittest.TestCase ): @slow @unittest.skip("""Model is not available.""" ) def _snake_case ( self :int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """nvidia/megatron-bert-uncased-345m""" if "MYDIR" in os.environ: SCREAMING_SNAKE_CASE__ = os.path.join(os.environ["""MYDIR"""] , __A ) SCREAMING_SNAKE_CASE__ = MegatronBertModel.from_pretrained(__A ) model.to(__A ) model.half() SCREAMING_SNAKE_CASE__ = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = [-0.6_0_4_0, -0.2_5_1_7, -0.1_0_2_5, 0.3_4_2_0, -0.6_7_5_8, -0.0_0_1_7, -0.1_0_8_9, -0.1_9_9_0, 0.5_7_2_8] for ii in range(3 ): for jj in range(3 ): SCREAMING_SNAKE_CASE__ = output[0, ii, jj] SCREAMING_SNAKE_CASE__ = expected[3 * ii + jj] SCREAMING_SNAKE_CASE__ = """ii={} jj={} a={} b={}""".format(__A , __A , __A , __A ) self.assertTrue(math.isclose(__A , __A , rel_tol=__A , abs_tol=__A ) , msg=__A )
6
from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nielsr/canine-s': 2048, } # Unicode defines 1,114,112 total “codepoints” _lowerCamelCase = 1114112 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py _lowerCamelCase = 0 _lowerCamelCase = 0XE0_00 _lowerCamelCase = 0XE0_01 _lowerCamelCase = 0XE0_02 _lowerCamelCase = 0XE0_03 _lowerCamelCase = 0XE0_04 # Maps special codepoints to human-readable names. _lowerCamelCase = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. _lowerCamelCase = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self :str , __A :str=chr(__A ) , __A :str=chr(__A ) , __A :Dict=chr(__A ) , __A :str=chr(__A ) , __A :Union[str, Any]=chr(__A ) , __A :str=chr(__A ) , __A :int=False , __A :int=2048 , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , model_max_length=__A , **__A , ) # Creates a mapping for looking up the IDs of special symbols. SCREAMING_SNAKE_CASE__ = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): SCREAMING_SNAKE_CASE__ = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. SCREAMING_SNAKE_CASE__ = { codepoint: name for name, codepoint in self._special_codepoints.items() } SCREAMING_SNAKE_CASE__ = UNICODE_VOCAB_SIZE SCREAMING_SNAKE_CASE__ = len(self._special_codepoints ) @property def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" return self._unicode_vocab_size def _snake_case ( self :Tuple , __A :str ) -> List[str]: """simple docstring""" return list(__A ) def _snake_case ( self :Optional[Any] , __A :str ) -> int: """simple docstring""" try: return ord(__A ) except TypeError: raise ValueError(f'''invalid token: \'{token}\'''' ) def _snake_case ( self :str , __A :int ) -> str: """simple docstring""" try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(__A ) except TypeError: raise ValueError(f'''invalid id: {index}''' ) def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Any: """simple docstring""" return "".join(__A ) def _snake_case ( self :Optional[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] + ([0] * len(__A )) + [1] if token_ids_a is not None: result += ([0] * len(__A )) + [1] return result def _snake_case ( self :List[str] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] SCREAMING_SNAKE_CASE__ = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Any: """simple docstring""" return ()
6
1
import requests from bsa import BeautifulSoup def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str = "AAPL" ): SCREAMING_SNAKE_CASE__ = f'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}''' SCREAMING_SNAKE_CASE__ = BeautifulSoup(requests.get(UpperCamelCase__ ).text , """html.parser""" ) SCREAMING_SNAKE_CASE__ = """My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" , class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
6
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) _lowerCamelCase = 'bert-base-cased' _lowerCamelCase = 'fp16' _lowerCamelCase = 'bf16' _lowerCamelCase = [FPaa, BFaa] @require_fsdp @require_cuda class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = dict( ACCELERATE_USE_FSDP="""true""" , MASTER_ADDR="""localhost""" , MASTER_PORT="""10999""" , RANK="""0""" , LOCAL_RANK="""0""" , WORLD_SIZE="""1""" , ) def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = f'''{i + 1}''' SCREAMING_SNAKE_CASE__ = strategy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def _snake_case ( self :int ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = prefetch_policy with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = state_dict_type with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoModel.from_pretrained(__A ) for policy in FSDP_AUTO_WRAP_POLICY: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = policy if policy == "TRANSFORMER_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """BertLayer""" elif policy == "SIZE_BASED_WRAP": SCREAMING_SNAKE_CASE__ = """2000""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """TRANSFORMER_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """T5Layer""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() with self.assertRaises(__A ) as cm: fsdp_plugin.set_auto_wrap_policy(__A ) self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception ) ) SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = """SIZE_BASED_WRAP""" SCREAMING_SNAKE_CASE__ = """0""" with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(__A ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = mp_dtype with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = Accelerator() if mp_dtype == "fp16": SCREAMING_SNAKE_CASE__ = torch.floataa elif mp_dtype == "bf16": SCREAMING_SNAKE_CASE__ = torch.bfloataa SCREAMING_SNAKE_CASE__ = MixedPrecision(param_dtype=__A , reduce_dtype=__A , buffer_dtype=__A ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , __A ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , __A ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(__A ) def _snake_case ( self :str ) -> str: """simple docstring""" from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: SCREAMING_SNAKE_CASE__ = self.dist_env.copy() SCREAMING_SNAKE_CASE__ = str(__A ).lower() with mockenv_context(**__A ): SCREAMING_SNAKE_CASE__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=__A ) ) @require_fsdp @require_multi_gpu @slow class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Any ) -> Any: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = 0.8_2 SCREAMING_SNAKE_CASE__ = [ """fsdp_shard_grad_op_transformer_based_wrap""", """fsdp_full_shard_transformer_based_wrap""", ] SCREAMING_SNAKE_CASE__ = { """multi_gpu_fp16""": 3200, """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2000, """fsdp_full_shard_transformer_based_wrap_fp16""": 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = 160 SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps"""] ) def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_performance.py""" ) SCREAMING_SNAKE_CASE__ = ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""] for config in self.performance_configs: SCREAMING_SNAKE_CASE__ = cmd.copy() for i, strategy in enumerate(__A ): if strategy.lower() in config: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "fp32" in config: cmd_config.append("""--mixed_precision=no""" ) else: cmd_config.append("""--mixed_precision=fp16""" ) if "cpu_offload" in config: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--performance_lower_bound={self.performance_lower_bound}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_checkpointing.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp""", """--mixed_precision=fp16""", """--fsdp_transformer_layer_cls_to_wrap=BertLayer""", ] for i, strategy in enumerate(__A ): SCREAMING_SNAKE_CASE__ = cmd.copy() cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) if strategy != "FULL_SHARD": continue SCREAMING_SNAKE_CASE__ = len(__A ) for state_dict_type in FSDP_STATE_DICT_TYPE: SCREAMING_SNAKE_CASE__ = cmd_config[:state_dict_config_index] cmd_config.append(f'''--fsdp_state_dict_type={state_dict_type}''' ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', """--partial_train_epoch=1""", ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) SCREAMING_SNAKE_CASE__ = cmd_config[:-1] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdir , """epoch_0""" ) cmd_config.extend( [ f'''--resume_from_checkpoint={resume_from_checkpoint}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.test_scripts_folder , """test_peak_memory_usage.py""" ) SCREAMING_SNAKE_CASE__ = [ """accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): SCREAMING_SNAKE_CASE__ = cmd.copy() if "fp16" in spec: cmd_config.extend(["""--mixed_precision=fp16"""] ) else: cmd_config.extend(["""--mixed_precision=no"""] ) if "multi_gpu" in spec: continue else: cmd_config.extend(["""--use_fsdp"""] ) for i, strategy in enumerate(__A ): if strategy.lower() in spec: cmd_config.append(f'''--fsdp_sharding_strategy={i+1}''' ) break if "cpu_offload" in spec: cmd_config.append("""--fsdp_offload_params=True""" ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(f'''--fsdp_auto_wrap_policy={policy}''' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("""--fsdp_transformer_layer_cls_to_wrap=BertLayer""" ) elif policy == "SIZE_BASED_WRAP": cmd_config.append("""--fsdp_min_num_params=2000""" ) cmd_config.extend( [ self.test_file_path, f'''--output_dir={self.tmpdir}''', f'''--peak_memory_upper_bound={peak_mem_upper_bound}''', f'''--n_train={self.n_train}''', f'''--n_val={self.n_val}''', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() )
6
1
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = [ ['attention', 'attn'], ['encoder_attention', 'encoder_attn'], ['q_lin', 'q_proj'], ['k_lin', 'k_proj'], ['v_lin', 'v_proj'], ['out_lin', 'out_proj'], ['norm_embeddings', 'layernorm_embedding'], ['position_embeddings', 'embed_positions'], ['embeddings', 'embed_tokens'], ['ffn.lin', 'fc'], ] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: SCREAMING_SNAKE_CASE__ = k.replace(UpperCamelCase__ , UpperCamelCase__ ) if k.startswith("""encoder""" ): SCREAMING_SNAKE_CASE__ = k.replace(""".attn""" , """.self_attn""" ) SCREAMING_SNAKE_CASE__ = k.replace("""norm1""" , """self_attn_layer_norm""" ) SCREAMING_SNAKE_CASE__ = k.replace("""norm2""" , """final_layer_norm""" ) elif k.startswith("""decoder""" ): SCREAMING_SNAKE_CASE__ = k.replace("""norm1""" , """self_attn_layer_norm""" ) SCREAMING_SNAKE_CASE__ = k.replace("""norm2""" , """encoder_attn_layer_norm""" ) SCREAMING_SNAKE_CASE__ = k.replace("""norm3""" , """final_layer_norm""" ) return k def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [ """model.encoder.layernorm_embedding.weight""", """model.encoder.layernorm_embedding.bias""", """model.decoder.layernorm_embedding.weight""", """model.decoder.layernorm_embedding.bias""", ] for k in keys: SCREAMING_SNAKE_CASE__ = sd.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = k.replace("""layernorm_embedding""" , """layer_norm""" ) assert new_k not in sd SCREAMING_SNAKE_CASE__ = v _lowerCamelCase = ['START'] @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Any , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ = model["""model"""] SCREAMING_SNAKE_CASE__ = BlenderbotConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BlenderbotForConditionalGeneration(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = m.model.state_dict().keys() SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue SCREAMING_SNAKE_CASE__ = rename_state_dict_key(UpperCamelCase__ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: SCREAMING_SNAKE_CASE__ = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(UpperCamelCase__ ) m.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) m.half() m.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument('--src_path', type=str, help='like blenderbot-model.bin') parser.add_argument('--save_dir', default='hf_blenderbot', type=str, help='Where to save converted model.') parser.add_argument( '--hf_config_json', default='blenderbot-3b-config.json', type=str, help='Path to config to use' ) _lowerCamelCase = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
6
import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig _lowerCamelCase = logging.get_logger(__name__) # General docstring _lowerCamelCase = 'PoolFormerConfig' # Base docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = [1, 512, 7, 7] # Image classification docstring _lowerCamelCase = 'sail/poolformer_s12' _lowerCamelCase = 'tabby, tabby cat' _lowerCamelCase = [ 'sail/poolformer_s12', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: float = 0.0 , UpperCamelCase__: bool = False ): if drop_prob == 0.0 or not training: return input SCREAMING_SNAKE_CASE__ = 1 - drop_prob SCREAMING_SNAKE_CASE__ = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets SCREAMING_SNAKE_CASE__ = keep_prob + torch.rand(UpperCamelCase__ , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize SCREAMING_SNAKE_CASE__ = input.div(UpperCamelCase__ ) * random_tensor return output class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Optional[float] = None ) -> None: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = drop_prob def _snake_case ( self :Any , __A :torch.Tensor ) -> torch.Tensor: """simple docstring""" return drop_path(__A , self.drop_prob , self.training ) def _snake_case ( self :Dict ) -> str: """simple docstring""" return "p={}".format(self.drop_prob ) class UpperCamelCase_ ( nn.Module ): def __init__( self :Dict , __A :Optional[Any] , __A :Dict , __A :List[str] , __A :Optional[Any] , __A :Tuple , __A :Optional[Any]=None ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = patch_size if isinstance(__A , collections.abc.Iterable ) else (patch_size, patch_size) SCREAMING_SNAKE_CASE__ = stride if isinstance(__A , collections.abc.Iterable ) else (stride, stride) SCREAMING_SNAKE_CASE__ = padding if isinstance(__A , collections.abc.Iterable ) else (padding, padding) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , kernel_size=__A , stride=__A , padding=__A ) SCREAMING_SNAKE_CASE__ = norm_layer(__A ) if norm_layer else nn.Identity() def _snake_case ( self :Dict , __A :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.projection(__A ) SCREAMING_SNAKE_CASE__ = self.norm(__A ) return embeddings class UpperCamelCase_ ( nn.GroupNorm ): def __init__( self :Dict , __A :Tuple , **__A :Union[str, Any] ) -> Dict: """simple docstring""" super().__init__(1 , __A , **__A ) class UpperCamelCase_ ( nn.Module ): def __init__( self :List[str] , __A :Optional[int] ) -> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.AvgPoolad(__A , stride=1 , padding=pool_size // 2 , count_include_pad=__A ) def _snake_case ( self :Any , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" return self.pool(__A ) - hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[Any] , __A :Tuple , __A :Dict , __A :int , __A :Any ) -> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if isinstance(config.hidden_act , __A ): SCREAMING_SNAKE_CASE__ = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE__ = config.hidden_act def _snake_case ( self :Union[str, Any] , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.act_fn(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) SCREAMING_SNAKE_CASE__ = self.conva(__A ) SCREAMING_SNAKE_CASE__ = self.drop(__A ) return hidden_states class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :str , __A :List[str] , __A :Tuple , __A :Dict , __A :Union[str, Any] , __A :int ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = PoolFormerPooling(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerOutput(__A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(__A ) # Useful for training neural nets SCREAMING_SNAKE_CASE__ = PoolFormerDropPath(__A ) if drop_path > 0.0 else nn.Identity() SCREAMING_SNAKE_CASE__ = config.use_layer_scale if config.use_layer_scale: SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) SCREAMING_SNAKE_CASE__ = nn.Parameter( config.layer_scale_init_value * torch.ones((__A) ) , requires_grad=__A ) def _snake_case ( self :Optional[Any] , __A :Optional[int] ) -> str: """simple docstring""" if self.use_layer_scale: SCREAMING_SNAKE_CASE__ = self.pooling(self.before_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = () SCREAMING_SNAKE_CASE__ = self.output(self.after_norm(__A ) ) SCREAMING_SNAKE_CASE__ = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection SCREAMING_SNAKE_CASE__ = hidden_states + self.drop_path(__A ) SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs else: SCREAMING_SNAKE_CASE__ = self.drop_path(self.pooling(self.before_norm(__A ) ) ) # First residual connection SCREAMING_SNAKE_CASE__ = pooling_output + hidden_states SCREAMING_SNAKE_CASE__ = () # Second residual connection inside the PoolFormerOutput block SCREAMING_SNAKE_CASE__ = self.drop_path(self.output(self.after_norm(__A ) ) ) SCREAMING_SNAKE_CASE__ = hidden_states + layer_output SCREAMING_SNAKE_CASE__ = (output,) + outputs return outputs class UpperCamelCase_ ( nn.Module ): def __init__( self :Union[str, Any] , __A :List[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = config # stochastic depth decay rule SCREAMING_SNAKE_CASE__ = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings SCREAMING_SNAKE_CASE__ = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) # Transformer blocks SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers SCREAMING_SNAKE_CASE__ = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__A ) ) SCREAMING_SNAKE_CASE__ = nn.ModuleList(__A ) def _snake_case ( self :str , __A :Tuple , __A :Dict=False , __A :Tuple=True ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = () if output_hidden_states else None SCREAMING_SNAKE_CASE__ = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = layers # Get patch embeddings from hidden_states SCREAMING_SNAKE_CASE__ = embedding_layer(__A ) # Send the embeddings through the blocks for _, blk in enumerate(__A ): SCREAMING_SNAKE_CASE__ = blk(__A ) SCREAMING_SNAKE_CASE__ = layer_outputs[0] if output_hidden_states: SCREAMING_SNAKE_CASE__ = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__A , hidden_states=__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = PoolFormerConfig lowerCamelCase_ = "poolformer" lowerCamelCase_ = "pixel_values" lowerCamelCase_ = True def _snake_case ( self :Optional[Any] , __A :Tuple ) -> Dict: """simple docstring""" if isinstance(__A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _snake_case ( self :str , __A :Optional[Any] , __A :Union[str, Any]=False ) -> Any: """simple docstring""" if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = value _lowerCamelCase = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _lowerCamelCase = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n' @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Any ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config SCREAMING_SNAKE_CASE__ = PoolFormerEncoder(__A ) # Initialize weights and apply final processing self.post_init() def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _snake_case ( self :Dict , __A :Optional[torch.FloatTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) SCREAMING_SNAKE_CASE__ = self.encoder( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__A , hidden_states=encoder_outputs.hidden_states , ) class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :Optional[int] ) -> Tuple: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Linear(config.hidden_size , config.hidden_size ) def _snake_case ( self :List[Any] , __A :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dense(__A ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , UpperCamelCase__ , ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :str , __A :Union[str, Any] ) -> int: """simple docstring""" super().__init__(__A ) SCREAMING_SNAKE_CASE__ = config.num_labels SCREAMING_SNAKE_CASE__ = PoolFormerModel(__A ) # Final norm SCREAMING_SNAKE_CASE__ = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head SCREAMING_SNAKE_CASE__ = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _snake_case ( self :int , __A :Optional[torch.FloatTensor] = None , __A :Optional[torch.LongTensor] = None , __A :Optional[bool] = None , __A :Optional[bool] = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: """simple docstring""" SCREAMING_SNAKE_CASE__ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE__ = self.poolformer( __A , output_hidden_states=__A , return_dict=__A , ) SCREAMING_SNAKE_CASE__ = outputs[0] SCREAMING_SNAKE_CASE__ = self.classifier(self.norm(__A ).mean([-2, -1] ) ) SCREAMING_SNAKE_CASE__ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE__ = """single_label_classification""" else: SCREAMING_SNAKE_CASE__ = """multi_label_classification""" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE__ = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE__ = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE__ = CrossEntropyLoss() SCREAMING_SNAKE_CASE__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE__ = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE__ = loss_fct(__A , __A ) if not return_dict: SCREAMING_SNAKE_CASE__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__A , logits=__A , hidden_states=outputs.hidden_states )
6
1
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = (DDIMParallelScheduler,) lowerCamelCase_ = (("eta", 0.0), ("num_inference_steps", 50)) def _snake_case ( self :List[Any] , **__A :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = { """num_train_timesteps""": 1000, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """clip_sample""": True, } config.update(**__A ) return config def _snake_case ( self :int , **__A :List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ = self.get_scheduler_config(**__A ) SCREAMING_SNAKE_CASE__ = scheduler_class(**__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 10, 0.0 SCREAMING_SNAKE_CASE__ = self.dummy_model() SCREAMING_SNAKE_CASE__ = self.dummy_sample_deter scheduler.set_timesteps(__A ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ = model(__A , __A ) SCREAMING_SNAKE_CASE__ = scheduler.step(__A , __A , __A , __A ).prev_sample return sample def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__A ) def _snake_case ( self :Union[str, Any] ) -> Tuple: """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__A ) SCREAMING_SNAKE_CASE__ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ = self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE__ = scheduler_class(**__A ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def _snake_case ( self :List[str] ) -> 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=__A , beta_end=__A ) def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__A ) def _snake_case ( self :int ) -> List[Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__A ) def _snake_case ( self :Optional[Any] ) -> List[Any]: """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=__A ) def _snake_case ( self :Any ) -> Any: """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__A ) def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__A ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" self.check_over_configs(thresholding=__A ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__A , prediction_type=__A , sample_max_value=__A , ) def _snake_case ( self :Optional[int] ) -> List[Any]: """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=__A ) def _snake_case ( self :str ) -> Tuple: """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__A , num_inference_steps=__A ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__A , eta=__A ) def _snake_case ( self :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ = scheduler_class(**__A ) 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 _snake_case ( self :int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ = scheduler_class(**__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 10, 0.0 scheduler.set_timesteps(__A ) SCREAMING_SNAKE_CASE__ = self.dummy_model() SCREAMING_SNAKE_CASE__ = self.dummy_sample_deter SCREAMING_SNAKE_CASE__ = self.dummy_sample_deter + 0.1 SCREAMING_SNAKE_CASE__ = self.dummy_sample_deter - 0.1 SCREAMING_SNAKE_CASE__ = samplea.shape[0] SCREAMING_SNAKE_CASE__ = torch.stack([samplea, samplea, samplea] , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.arange(__A )[0:3, None].repeat(1 , __A ) SCREAMING_SNAKE_CASE__ = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE__ = scheduler.batch_step_no_noise(__A , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __A ) SCREAMING_SNAKE_CASE__ = torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE__ = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_1_4_7.7_9_0_4 ) < 1E-2 assert abs(result_mean.item() - 0.4_9_8_2 ) < 1E-3 def _snake_case ( self :Tuple ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.full_loop() SCREAMING_SNAKE_CASE__ = torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE__ = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_7_2.0_0_6_7 ) < 1E-2 assert abs(result_mean.item() - 0.2_2_3_9_6_7 ) < 1E-3 def _snake_case ( self :Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.full_loop(prediction_type="""v_prediction""" ) SCREAMING_SNAKE_CASE__ = torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE__ = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 5_2.5_3_0_2 ) < 1E-2 assert abs(result_mean.item() - 0.0_6_8_4 ) < 1E-3 def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.full_loop(set_alpha_to_one=__A , beta_start=0.0_1 ) SCREAMING_SNAKE_CASE__ = torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE__ = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_4_9.8_2_9_5 ) < 1E-2 assert abs(result_mean.item() - 0.1_9_5_1 ) < 1E-3 def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.full_loop(set_alpha_to_one=__A , beta_start=0.0_1 ) SCREAMING_SNAKE_CASE__ = torch.sum(torch.abs(__A ) ) SCREAMING_SNAKE_CASE__ = torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_4_9.0_7_8_4 ) < 1E-2 assert abs(result_mean.item() - 0.1_9_4_1 ) < 1E-3
6
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device 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 ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Union[str, Any] , __A :Optional[int] , __A :Tuple=13 , __A :Dict=7 , __A :Dict=True , __A :str=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Optional[Any]=True , __A :Any=False , __A :Dict=False , __A :Any=False , __A :Tuple=2 , __A :Dict=99 , __A :Optional[Any]=0 , __A :List[str]=32 , __A :Optional[int]=5 , __A :Dict=4 , __A :List[str]=0.1 , __A :Union[str, Any]=0.1 , __A :Tuple=512 , __A :Any=12 , __A :Optional[int]=2 , __A :Union[str, Any]=0.0_2 , __A :Dict=3 , __A :Optional[int]=4 , __A :Any="last" , __A :List[Any]=None , __A :Any=None , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_lengths SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = gelu_activation SCREAMING_SNAKE_CASE__ = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ = causal SCREAMING_SNAKE_CASE__ = asm SCREAMING_SNAKE_CASE__ = n_langs SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_special SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = summary_type SCREAMING_SNAKE_CASE__ = use_proj SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_input_lengths: SCREAMING_SNAKE_CASE__ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , 2 ).float() SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def _snake_case ( self :Tuple , __A :str , __A :int , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[int] , __A :Union[str, Any] , __A :Union[str, Any] , __A :str , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , lengths=__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A , langs=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :str , __A :Any , __A :str , __A :Union[str, Any] , __A :Optional[Any] , __A :Optional[int] , __A :Any , __A :Union[str, Any] , __A :Optional[Any] , __A :Union[str, Any] , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertWithLMHeadModel(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , token_type_ids=__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Tuple , __A :Union[str, Any] , __A :Optional[Any] , __A :Dict , __A :Dict , __A :Union[str, Any] , __A :List[str] , __A :Optional[int] , __A :int , __A :str , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnsweringSimple(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :List[str] , __A :Any , __A :int , __A :Tuple , __A :Optional[Any] , __A :Tuple , __A :Optional[int] , __A :str , __A :int , __A :str , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForQuestionAnswering(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , p_mask=__A , ) SCREAMING_SNAKE_CASE__ = model( __A , start_positions=__A , end_positions=__A , cls_index=__A , is_impossible=__A , ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE__ = model(__A , start_positions=__A , end_positions=__A ) ((SCREAMING_SNAKE_CASE__) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _snake_case ( self :Optional[int] , __A :str , __A :Optional[int] , __A :Tuple , __A :Dict , __A :List[str] , __A :Tuple , __A :List[str] , __A :Dict , __A :List[str] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self :Optional[Any] , __A :Optional[Any] , __A :Optional[Any] , __A :List[str] , __A :Optional[Any] , __A :int , __A :Tuple , __A :Optional[int] , __A :Union[str, Any] , __A :Dict , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = FlaubertForTokenClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :str , __A :Any , __A :Tuple , __A :List[str] , __A :Tuple , __A :Any , __A :int , __A :Dict , __A :List[str] , __A :Tuple , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = FlaubertForMultipleChoice(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) lowerCamelCase_ = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _snake_case ( self :Any , __A :Optional[int] , __A :Optional[int] , __A :Dict , __A :List[Any] , __A :Tuple ) -> str: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _snake_case ( self :Tuple , __A :List[str] , __A :Optional[int] , __A :Dict=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super()._prepare_for_class(__A , __A , return_labels=__A ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) return inputs_dict def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , emb_dim=37 ) def _snake_case ( self :int ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__A ) def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__A ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*__A ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__A ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__A ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*__A ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*__A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @slow @require_torch_gpu def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = model_class(config=__A ) SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = torch.jit.trace( __A , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__A , os.path.join(__A , """traced_model.pt""" ) ) SCREAMING_SNAKE_CASE__ = torch.jit.load(os.path.join(__A , """traced_model.pt""" ) , map_location=__A ) loaded(inputs_dict["""input_ids"""].to(__A ) , inputs_dict["""attention_mask"""].to(__A ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [[[-2.6_2_5_1, -1.4_2_9_8, -0.0_2_2_7], [-2.8_5_1_0, -1.6_3_8_7, 0.2_2_5_8], [-2.8_1_1_4, -1.1_8_3_2, -0.3_0_6_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=1E-4 ) )
6
1
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[Any]=None ): SCREAMING_SNAKE_CASE__ = None if token is not None: SCREAMING_SNAKE_CASE__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , headers=UpperCamelCase__ ).json() SCREAMING_SNAKE_CASE__ = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) SCREAMING_SNAKE_CASE__ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = requests.get(url + f'''&page={i + 2}''' , headers=UpperCamelCase__ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: str=None ): SCREAMING_SNAKE_CASE__ = None if token is not None: SCREAMING_SNAKE_CASE__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , headers=UpperCamelCase__ ).json() SCREAMING_SNAKE_CASE__ = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) SCREAMING_SNAKE_CASE__ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = requests.get(url + f'''&page={i + 2}''' , headers=UpperCamelCase__ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = None if token is not None: SCREAMING_SNAKE_CASE__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , headers=UpperCamelCase__ , allow_redirects=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = result.headers["""Location"""] SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , allow_redirects=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''{artifact_name}.zip''' ) with open(UpperCamelCase__ , """wb""" ) as fp: fp.write(response.content ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = None with zipfile.ZipFile(UpperCamelCase__ ) as z: for filename in z.namelist(): if not os.path.isdir(UpperCamelCase__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(UpperCamelCase__ ) as f: for line in f: SCREAMING_SNAKE_CASE__ = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs SCREAMING_SNAKE_CASE__ = line[: line.index(""": """ )] SCREAMING_SNAKE_CASE__ = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed SCREAMING_SNAKE_CASE__ = line[len("""FAILED """ ) :] failed_tests.append(UpperCamelCase__ ) elif filename == "job_name.txt": SCREAMING_SNAKE_CASE__ = line if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(UpperCamelCase__ )} for `errors` ''' f'''and {len(UpperCamelCase__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) SCREAMING_SNAKE_CASE__ = None if job_name and job_links: SCREAMING_SNAKE_CASE__ = job_links.get(UpperCamelCase__ , UpperCamelCase__ ) # A list with elements of the form (line of error, error, failed test) SCREAMING_SNAKE_CASE__ = [x + [y] + [job_link] for x, y in zip(UpperCamelCase__ , UpperCamelCase__ )] return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [os.path.join(UpperCamelCase__ , UpperCamelCase__ ) for p in os.listdir(UpperCamelCase__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(UpperCamelCase__ , job_links=UpperCamelCase__ ) ) return errors def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: str=None ): SCREAMING_SNAKE_CASE__ = Counter() counter.update([x[1] for x in logs] ) SCREAMING_SNAKE_CASE__ = counter.most_common() SCREAMING_SNAKE_CASE__ = {} for error, count in counts: if error_filter is None or error not in error_filter: SCREAMING_SNAKE_CASE__ = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} SCREAMING_SNAKE_CASE__ = dict(sorted(r.items() , key=lambda UpperCamelCase__ : item[1]["count"] , reverse=UpperCamelCase__ ) ) return r def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): SCREAMING_SNAKE_CASE__ = test.split("""/""" )[2] else: SCREAMING_SNAKE_CASE__ = None return test def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = [(x[0], x[1], get_model(x[2] )) for x in logs] SCREAMING_SNAKE_CASE__ = [x for x in logs if x[2] is not None] SCREAMING_SNAKE_CASE__ = {x[2] for x in logs} SCREAMING_SNAKE_CASE__ = {} for test in tests: SCREAMING_SNAKE_CASE__ = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) SCREAMING_SNAKE_CASE__ = counter.most_common() SCREAMING_SNAKE_CASE__ = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} SCREAMING_SNAKE_CASE__ = sum(error_counts.values() ) if n_errors > 0: SCREAMING_SNAKE_CASE__ = {"""count""": n_errors, """errors""": error_counts} SCREAMING_SNAKE_CASE__ = dict(sorted(r.items() , key=lambda UpperCamelCase__ : item[1]["count"] , reverse=UpperCamelCase__ ) ) return r def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = """| no. | error | status |""" SCREAMING_SNAKE_CASE__ = """|-:|:-|:-|""" SCREAMING_SNAKE_CASE__ = [header, sep] for error in reduced_by_error: SCREAMING_SNAKE_CASE__ = reduced_by_error[error]["""count"""] SCREAMING_SNAKE_CASE__ = f'''| {count} | {error[:100]} | |''' lines.append(UpperCamelCase__ ) return "\n".join(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = """| model | no. of errors | major error | count |""" SCREAMING_SNAKE_CASE__ = """|-:|-:|-:|-:|""" SCREAMING_SNAKE_CASE__ = [header, sep] for model in reduced_by_model: SCREAMING_SNAKE_CASE__ = reduced_by_model[model]["""count"""] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = list(reduced_by_model[model]["""errors"""].items() )[0] SCREAMING_SNAKE_CASE__ = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(UpperCamelCase__ ) return "\n".join(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') parser.add_argument( '--output_dir', type=str, required=True, help='Where to store the downloaded artifacts and other result files.', ) parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.') _lowerCamelCase = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _lowerCamelCase = get_job_links(args.workflow_run_id, token=args.token) _lowerCamelCase = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _lowerCamelCase = k.find(' / ') _lowerCamelCase = k[index + len(' / ') :] _lowerCamelCase = v with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _lowerCamelCase = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _lowerCamelCase = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _lowerCamelCase = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _lowerCamelCase = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _lowerCamelCase = reduce_by_error(errors) _lowerCamelCase = reduce_by_model(errors) _lowerCamelCase = make_github_table(reduced_by_error) _lowerCamelCase = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa) with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa)
6
from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})''' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple=True ): model.train() SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = F.mse_loss(UpperCamelCase__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[Any]=False ): set_seed(42 ) SCREAMING_SNAKE_CASE__ = RegressionModel() SCREAMING_SNAKE_CASE__ = deepcopy(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) model.to(accelerator.device ) if sched: SCREAMING_SNAKE_CASE__ = AdamW(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = AdamW(params=ddp_model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) SCREAMING_SNAKE_CASE__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) # Make a copy of `model` if sched: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): # Test when on a single CPU or GPU that the context manager does nothing SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): # Test on distributed setup that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) # Use a single batch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next(iter(UpperCamelCase__ ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int=False , UpperCamelCase__: Union[str, Any]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(UpperCamelCase__ ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), f'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})''' else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), f'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})''' # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) SCREAMING_SNAKE_CASE__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple=False , UpperCamelCase__: List[str]=False ): SCREAMING_SNAKE_CASE__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_training_setup(UpperCamelCase__ , UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = batch.values() # Gather the distributed inputs and targs for the base model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.gather((ddp_input, ddp_target) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCamelCase__ )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), f'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n''' SCREAMING_SNAKE_CASE__ = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(UpperCamelCase__ )) if accelerator.num_processes > 1: check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = RegressionDataset(length=80 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ = RegressionDataset(length=96 ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=16 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if iteration < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if batch_num < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Accelerator() SCREAMING_SNAKE_CASE__ = accelerator.state if state.local_process_index == 0: print("""**Test `accumulate` gradient accumulation with dataloader break**""" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("""**Test NOOP `no_sync` context manager**""" ) test_noop_sync(UpperCamelCase__ ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("""**Test Distributed `no_sync` context manager**""" ) test_distributed_sync(UpperCamelCase__ ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation(UpperCamelCase__ , UpperCamelCase__ ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("""<""" , """2.0""" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , """`split_batches=False`, `dispatch_batches=False`**""" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( """**Test `accumulate` gradient accumulation with optimizer and scheduler, """ , f'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**''' , ) test_gradient_accumulation_with_opt_and_scheduler(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
6
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Union[str, Any]=False ): SCREAMING_SNAKE_CASE__ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''deit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''deit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''deit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''deit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''deit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''deit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''deit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''deit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''deit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''deit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" SCREAMING_SNAKE_CASE__ = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any]=False ): for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE__ = """""" else: SCREAMING_SNAKE_CASE__ = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-config.hidden_size :] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = DeiTConfig() # all deit models have fine-tuned heads SCREAMING_SNAKE_CASE__ = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = int(deit_name[-6:-4] ) SCREAMING_SNAKE_CASE__ = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): SCREAMING_SNAKE_CASE__ = 192 SCREAMING_SNAKE_CASE__ = 768 SCREAMING_SNAKE_CASE__ = 12 SCREAMING_SNAKE_CASE__ = 3 elif deit_name[9:].startswith("""small""" ): SCREAMING_SNAKE_CASE__ = 384 SCREAMING_SNAKE_CASE__ = 1_536 SCREAMING_SNAKE_CASE__ = 12 SCREAMING_SNAKE_CASE__ = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): SCREAMING_SNAKE_CASE__ = 1_024 SCREAMING_SNAKE_CASE__ = 4_096 SCREAMING_SNAKE_CASE__ = 24 SCREAMING_SNAKE_CASE__ = 16 # load original model from timm SCREAMING_SNAKE_CASE__ = timm.create_model(UpperCamelCase__ , pretrained=UpperCamelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ = timm_model.state_dict() SCREAMING_SNAKE_CASE__ = create_rename_keys(UpperCamelCase__ , UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) read_in_q_k_v(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # load HuggingFace model SCREAMING_SNAKE_CASE__ = DeiTForImageClassificationWithTeacher(UpperCamelCase__ ).eval() model.load_state_dict(UpperCamelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor SCREAMING_SNAKE_CASE__ = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 SCREAMING_SNAKE_CASE__ = DeiTImageProcessor(size=UpperCamelCase__ , crop_size=config.image_size ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = encoding["""pixel_values"""] SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = timm_model(UpperCamelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCamelCase__ , outputs.logits , atol=1e-3 ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) print(f'''Saving model {deit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--deit_name', default='vit_deit_base_distilled_patch16_224', type=str, help='Name of the DeiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _lowerCamelCase = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
6
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "AutoImageProcessor" lowerCamelCase_ = "AutoTokenizer" def __init__( self :Optional[int] , __A :Optional[Any] , __A :Dict ) -> Dict: """simple docstring""" super().__init__(__A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor def __call__( self :int , __A :str=None , __A :int=None , __A :Union[str, Any]=None , **__A :str ) -> Optional[Any]: """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :str , *__A :List[str] , **__A :List[str] ) -> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :List[str] , *__A :Any , **__A :Any ) -> Tuple: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
6
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE__ = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__A ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__A ) ) SCREAMING_SNAKE_CASE__ = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 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], } SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , __A ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__A , __A ) def _snake_case ( self :Optional[Any] , **__A :Optional[int] ) -> Union[str, Any]: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__A ) def _snake_case ( self :Optional[int] , **__A :List[str] ) -> Union[str, Any]: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__A ) def _snake_case ( self :str , **__A :Dict ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__A ) def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ = [Image.fromarray(np.moveaxis(__A , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=__A , image_processor=__A ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__A ) SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=__A , image_processor=__A ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __A ) self.assertIsInstance(processor_fast.tokenizer , __A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __A ) self.assertIsInstance(processor_fast.image_processor , __A ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) SCREAMING_SNAKE_CASE__ = self.get_image_processor(do_normalize=__A , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __A ) def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=__A , image_processor=__A ) SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = image_processor(__A , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ = processor(images=__A , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _snake_case ( self :Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=__A , image_processor=__A ) SCREAMING_SNAKE_CASE__ = """lower newer""" SCREAMING_SNAKE_CASE__ = processor(text=__A ) SCREAMING_SNAKE_CASE__ = tokenizer(__A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=__A , image_processor=__A ) SCREAMING_SNAKE_CASE__ = """lower newer""" SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = processor(text=__A , images=__A ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__A ): processor() def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=__A , image_processor=__A ) SCREAMING_SNAKE_CASE__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ = processor.batch_decode(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.batch_decode(__A ) self.assertListEqual(__A , __A ) def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_image_processor() SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = CLIPProcessor(tokenizer=__A , image_processor=__A ) SCREAMING_SNAKE_CASE__ = """lower newer""" SCREAMING_SNAKE_CASE__ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ = processor(text=__A , images=__A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ = True for i in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): SCREAMING_SNAKE_CASE__ = dp[i][j - 1] if arr[i - 1] <= j: SCREAMING_SNAKE_CASE__ = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: SCREAMING_SNAKE_CASE__ = s - 2 * j break return diff
6
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Union[str, Any]=4 , __A :Dict=3 , __A :str=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Tuple=[2, 4, 8, 16] , __A :List[str]=7 , __A :Optional[Any]=3.0 , __A :Tuple=True , __A :Tuple=0.0 , __A :Dict=0.0 , __A :Tuple=0.1 , __A :str="gelu" , __A :Tuple=0.0_2 , __A :str=1E-5 , __A :Tuple=0.0 , __A :List[str]=None , __A :Optional[Any]=None , **__A :Optional[Any] , ) -> List[str]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if mass < 0: raise ValueError("""The mass of a body cannot be negative""" ) return 0.5 * mass * abs(UpperCamelCase__ ) * abs(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
6
1
from __future__ import annotations class UpperCamelCase_ : def __init__( self :Tuple , __A :list[list[int]] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = TypeError( """Matrices must be formed from a list of zero or more lists containing at """ """least one and the same number of values, each of which must be of type """ """int or float.""" ) if len(__A ) != 0: SCREAMING_SNAKE_CASE__ = len(rows[0] ) if cols == 0: raise error for row in rows: if len(__A ) != cols: raise error for value in row: if not isinstance(__A , (int, float) ): raise error SCREAMING_SNAKE_CASE__ = rows else: SCREAMING_SNAKE_CASE__ = [] def _snake_case ( self :int ) -> list[list[int]]: """simple docstring""" return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )] @property def _snake_case ( self :List[Any] ) -> int: """simple docstring""" return len(self.rows ) @property def _snake_case ( self :Optional[int] ) -> int: """simple docstring""" return len(self.rows[0] ) @property def _snake_case ( self :Dict ) -> tuple[int, int]: """simple docstring""" return (self.num_rows, self.num_columns) @property def _snake_case ( self :Any ) -> bool: """simple docstring""" return self.order[0] == self.order[1] def _snake_case ( self :int ) -> Matrix: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows )] for row_num in range(self.num_rows ) ] return Matrix(__A ) def _snake_case ( self :List[Any] ) -> int: """simple docstring""" if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0] ) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns ) ) def _snake_case ( self :Any ) -> bool: """simple docstring""" return bool(self.determinant() ) def _snake_case ( self :str , __A :int , __A :int ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns ) if other_column != column ] for other_row in range(self.num_rows ) if other_row != row ] return Matrix(__A ).determinant() def _snake_case ( self :List[str] , __A :int , __A :int ) -> int: """simple docstring""" if (row + column) % 2 == 0: return self.get_minor(__A , __A ) return -1 * self.get_minor(__A , __A ) def _snake_case ( self :Dict ) -> Matrix: """simple docstring""" return Matrix( [ [self.get_minor(__A , __A ) for column in range(self.num_columns )] for row in range(self.num_rows ) ] ) def _snake_case ( self :List[Any] ) -> Matrix: """simple docstring""" return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns ) ] for row in range(self.minors().num_rows ) ] ) def _snake_case ( self :Tuple ) -> Matrix: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ [self.cofactors().rows[column][row] for column in range(self.num_columns )] for row in range(self.num_rows ) ] return Matrix(__A ) def _snake_case ( self :List[str] ) -> Matrix: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.determinant() if not determinant: raise TypeError("""Only matrices with a non-zero determinant have an inverse""" ) return self.adjugate() * (1 / determinant) def __repr__( self :Any ) -> str: """simple docstring""" return str(self.rows ) def __str__( self :Optional[Any] ) -> str: """simple docstring""" if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0] ) ) + "]]" return ( "[" + "\n ".join( [ """[""" + """. """.join([str(__A ) for value in row] ) + """.]""" for row in self.rows ] ) + "]" ) def _snake_case ( self :Optional[Any] , __A :list[int] , __A :int | None = None ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = TypeError("""Row must be a list containing all ints and/or floats""" ) if not isinstance(__A , __A ): raise type_error for value in row: if not isinstance(__A , (int, float) ): raise type_error if len(__A ) != self.num_columns: raise ValueError( """Row must be equal in length to the other rows in the matrix""" ) if position is None: self.rows.append(__A ) else: SCREAMING_SNAKE_CASE__ = self.rows[0:position] + [row] + self.rows[position:] def _snake_case ( self :List[str] , __A :list[int] , __A :int | None = None ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = TypeError( """Column must be a list containing all ints and/or floats""" ) if not isinstance(__A , __A ): raise type_error for value in column: if not isinstance(__A , (int, float) ): raise type_error if len(__A ) != self.num_rows: raise ValueError( """Column must be equal in length to the other columns in the matrix""" ) if position is None: SCREAMING_SNAKE_CASE__ = [self.rows[i] + [column[i]] for i in range(self.num_rows )] else: SCREAMING_SNAKE_CASE__ = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows ) ] def __eq__( self :Optional[int] , __A :object ) -> bool: """simple docstring""" if not isinstance(__A , __A ): return NotImplemented return self.rows == other.rows def __ne__( self :Dict , __A :object ) -> bool: """simple docstring""" return not self == other def __neg__( self :Optional[int] ) -> Matrix: """simple docstring""" return self * -1 def __add__( self :Dict , __A :Matrix ) -> Matrix: """simple docstring""" if self.order != other.order: raise ValueError("""Addition requires matrices of the same order""" ) return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __sub__( self :str , __A :Matrix ) -> Matrix: """simple docstring""" if self.order != other.order: raise ValueError("""Subtraction requires matrices of the same order""" ) return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __mul__( self :Optional[int] , __A :Matrix | int | float ) -> Matrix: """simple docstring""" if isinstance(__A , (int, float) ): return Matrix( [[int(element * other ) for element in row] for row in self.rows] ) elif isinstance(__A , __A ): if self.num_columns != other.num_rows: raise ValueError( """The number of columns in the first matrix must """ """be equal to the number of rows in the second""" ) return Matrix( [ [Matrix.dot_product(__A , __A ) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( """A Matrix can only be multiplied by an int, float, or another matrix""" ) def __pow__( self :str , __A :int ) -> Matrix: """simple docstring""" if not isinstance(__A , __A ): raise TypeError("""A Matrix can only be raised to the power of an int""" ) if not self.is_square: raise ValueError("""Only square matrices can be raised to a power""" ) if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( """Only invertable matrices can be raised to a negative power""" ) SCREAMING_SNAKE_CASE__ = self for _ in range(other - 1 ): result *= self return result @classmethod def _snake_case ( cls :str , __A :list[int] , __A :list[int] ) -> int: """simple docstring""" return sum(row[i] * column[i] for i in range(len(__A ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
6
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = True def __init__( self :Optional[int] , **__A :str ) -> int: """simple docstring""" super().__init__(**__A ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE__ = kwargs.pop("""encoder""" ) SCREAMING_SNAKE_CASE__ = encoder_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""decoder""" ) SCREAMING_SNAKE_CASE__ = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = True @classmethod def _snake_case ( cls :str , __A :PretrainedConfig , __A :PretrainedConfig , **__A :List[str] ) -> PretrainedConfig: """simple docstring""" logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__A ) def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.encoder.to_dict() SCREAMING_SNAKE_CASE__ = self.decoder.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
6
1
import numpy as np from PIL import Image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: np.ndarray , UpperCamelCase__: int , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ) if arr.shape[0] != arr.shape[1]: raise ValueError("""The input array is not a square matrix""" ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE__ = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape SCREAMING_SNAKE_CASE__ = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix SCREAMING_SNAKE_CASE__ = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 return updated_arr def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: np.ndarray , UpperCamelCase__: int , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ) if arr.shape[0] != arr.shape[1]: raise ValueError("""The input array is not a square matrix""" ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE__ = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape SCREAMING_SNAKE_CASE__ = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix SCREAMING_SNAKE_CASE__ = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='avgpooling', verbose=True) # Loading the image _lowerCamelCase = Image.open('path_to_image') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
6
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization lowerCamelCase_ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"text": Value("string" )} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "text" lowerCamelCase_ = "labels" def _snake_case ( self :Any , __A :Dict ) -> Optional[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] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :str ) -> Dict[str, str]: """simple docstring""" return { self.text_column: "text", self.label_column: "labels", }
6
1
import inspect import unittest from transformers import DecisionTransformerConfig, 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, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class UpperCamelCase_ : def __init__( self :int , __A :Any , __A :int=13 , __A :Optional[Any]=7 , __A :Any=6 , __A :List[Any]=17 , __A :List[str]=23 , __A :List[str]=11 , __A :Optional[Any]=True , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = act_dim SCREAMING_SNAKE_CASE__ = state_dim SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = max_length SCREAMING_SNAKE_CASE__ = is_training def _snake_case ( self :int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) SCREAMING_SNAKE_CASE__ = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) SCREAMING_SNAKE_CASE__ = floats_tensor((self.batch_size, self.seq_length, 1) ) SCREAMING_SNAKE_CASE__ = floats_tensor((self.batch_size, self.seq_length, 1) ) SCREAMING_SNAKE_CASE__ = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) SCREAMING_SNAKE_CASE__ = random_attention_mask((self.batch_size, self.seq_length) ) SCREAMING_SNAKE_CASE__ = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def _snake_case ( self :List[Any] , __A :Union[str, Any] , __A :str , __A :Dict , __A :Union[str, Any] , __A :Tuple , __A :Tuple , __A :Dict , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = DecisionTransformerModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , __A , __A , __A , __A , __A ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = { """states""": states, """actions""": actions, """rewards""": rewards, """returns_to_go""": returns_to_go, """timesteps""": timesteps, """attention_mask""": attention_mask, } return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = (DecisionTransformerModel,) if is_torch_available() else () lowerCamelCase_ = () lowerCamelCase_ = {"feature-extraction": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids lowerCamelCase_ = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = DecisionTransformerModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , hidden_size=37 ) def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) @slow def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = DecisionTransformerModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ = [ """states""", """actions""", """rewards""", """returns_to_go""", """timesteps""", """attention_mask""", ] self.assertListEqual(arg_names[: len(__A )] , __A ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = 2 # number of steps of autoregressive prediction we will perform SCREAMING_SNAKE_CASE__ = 10 # defined by the RL environment, may be normalized SCREAMING_SNAKE_CASE__ = DecisionTransformerModel.from_pretrained("""edbeeching/decision-transformer-gym-hopper-expert""" ) SCREAMING_SNAKE_CASE__ = model.to(__A ) SCREAMING_SNAKE_CASE__ = model.config torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = torch.randn(1 , 1 , config.state_dim ).to(device=__A , dtype=torch.floataa ) # env.reset() SCREAMING_SNAKE_CASE__ = torch.tensor( [[0.2_4_2_7_9_3, -0.2_8_6_9_3_0_7_4, 0.8_7_4_2_6_1_3], [0.6_7_8_1_5_2_7_4, -0.0_8_1_0_1_0_8_5, -0.1_2_9_5_2_1_4_7]] , device=__A ) SCREAMING_SNAKE_CASE__ = torch.tensor(__A , device=__A , dtype=torch.floataa ).reshape(1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ = state SCREAMING_SNAKE_CASE__ = torch.zeros(1 , 0 , config.act_dim , device=__A , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = torch.zeros(1 , 0 , device=__A , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = torch.tensor(0 , device=__A , dtype=torch.long ).reshape(1 , 1 ) for step in range(__A ): SCREAMING_SNAKE_CASE__ = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=__A )] , dim=1 ) SCREAMING_SNAKE_CASE__ = torch.cat([rewards, torch.zeros(1 , 1 , device=__A )] , dim=1 ) SCREAMING_SNAKE_CASE__ = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model( states=__A , actions=__A , rewards=__A , returns_to_go=__A , timesteps=__A , attention_mask=__A , return_dict=__A , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=__A , dtype=torch.floataa ), 1.0, False, {}, ) SCREAMING_SNAKE_CASE__ = action_pred[0, -1] SCREAMING_SNAKE_CASE__ = torch.cat([states, state] , dim=1 ) SCREAMING_SNAKE_CASE__ = returns_to_go[0, -1] - reward SCREAMING_SNAKE_CASE__ = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) SCREAMING_SNAKE_CASE__ = torch.cat( [timesteps, torch.ones((1, 1) , device=__A , dtype=torch.long ) * (step + 1)] , dim=1 )
6
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = model.config SCREAMING_SNAKE_CASE__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) SCREAMING_SNAKE_CASE__ = MBartConfig( is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , ) return encoder_config, decoder_config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if "encoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" ) if "decoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if name.startswith("""encoder""" ): if "layers" in name: SCREAMING_SNAKE_CASE__ = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "mask" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight""" if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias""" return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_split[3] ) SCREAMING_SNAKE_CASE__ = int(key_split[5] ) SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE__ = val[:dim, :] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ = val[-dim:, :] else: SCREAMING_SNAKE_CASE__ = val[:dim] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: SCREAMING_SNAKE_CASE__ = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): # load original model SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval() # load HuggingFace model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = original_model.state_dict() SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify results on scanned document SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" ) SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" SCREAMING_SNAKE_CASE__ = """When is the coffee break?""" SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>""" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: SCREAMING_SNAKE_CASE__ = """<s_cord>""" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": SCREAMING_SNAKE_CASE__ = """s_cord-v2>""" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>""" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt SCREAMING_SNAKE_CASE__ = """hello world""" else: raise ValueError("""Model name not supported""" ) SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[ """input_ids""" ] SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) # verify encoder hidden states SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) # verify decoder hidden states SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, 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 and processor to the 🤗 hub.', ) _lowerCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
6
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = set({"""(""", """[""", """{"""} ) SCREAMING_SNAKE_CASE__ = set({""")""", """]""", """}"""} ) SCREAMING_SNAKE_CASE__ = {"""{""": """}""", """[""": """]""", """(""": """)"""} for i in range(len(UpperCamelCase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(UpperCamelCase__ ) == 0 or (len(UpperCamelCase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(UpperCamelCase__ ) == 0 def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = input("""Enter sequence of brackets: """ ) if is_balanced(UpperCamelCase__ ): print(UpperCamelCase__ , """is balanced""" ) else: print(UpperCamelCase__ , """is not balanced""" ) if __name__ == "__main__": main()
6
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_euler""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type="""np""" ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) SCREAMING_SNAKE_CASE__ = sd_pipe.to(__A ) sd_pipe.set_progress_bar_config(disable=__A ) sd_pipe.set_scheduler("""sample_dpmpp_2m""" ) SCREAMING_SNAKE_CASE__ = """A painting of a squirrel eating a burger""" SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = sd_pipe( [prompt] , generator=__A , guidance_scale=7.5 , num_inference_steps=15 , output_type="""np""" , use_karras_sigmas=__A , ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
6
1
# Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): return 1 / (1 + np.exp(-z )) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Tuple ): return (-y * np.log(UpperCamelCase__ ) - (1 - y) * np.log(1 - h )).mean() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) return np.sum(y * scores - np.log(1 + np.exp(UpperCamelCase__ ) ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str] , UpperCamelCase__: Any , UpperCamelCase__: Optional[Any]=70_000 ): SCREAMING_SNAKE_CASE__ = np.zeros(x.shape[1] ) for iterations in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sigmoid_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.dot(x.T , h - y ) / y.size SCREAMING_SNAKE_CASE__ = theta - alpha * gradient # updating the weights SCREAMING_SNAKE_CASE__ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = sigmoid_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = 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__": _lowerCamelCase = datasets.load_iris() _lowerCamelCase = iris.data[:, :2] _lowerCamelCase = (iris.target != 0) * 1 _lowerCamelCase = 0.1 _lowerCamelCase = logistic_reg(alpha, x, y, max_iterations=70000) print('theta: ', theta) # printing the theta i.e our weights vector def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): return sigmoid_function( np.dot(UpperCamelCase__ , UpperCamelCase__ ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 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') ((_lowerCamelCase) , (_lowerCamelCase)) = (x[:, 0].min(), x[:, 0].max()) ((_lowerCamelCase) , (_lowerCamelCase)) = (x[:, 1].min(), x[:, 1].max()) ((_lowerCamelCase) , (_lowerCamelCase)) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) _lowerCamelCase = np.c_[xxa.ravel(), xxa.ravel()] _lowerCamelCase = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='black') plt.legend() plt.show()
6
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 600_851_475_143 ): try: SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 while i * i <= n: while n % i == 0: SCREAMING_SNAKE_CASE__ = i n //= i i += 1 if n > 1: SCREAMING_SNAKE_CASE__ = n return int(UpperCamelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
6
1
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node _lowerCamelCase = 4 _lowerCamelCase = 3 class UpperCamelCase_ ( UpperCamelCase__ ): pass def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): for shard in shards: for i in range(UpperCamelCase__ ): yield {"i": i, "shard": shard} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = int(os.environ["""RANK"""] ) SCREAMING_SNAKE_CASE__ = int(os.environ["""WORLD_SIZE"""] ) SCREAMING_SNAKE_CASE__ = ArgumentParser() parser.add_argument("""--streaming""" , type=UpperCamelCase__ ) parser.add_argument("""--local_rank""" , type=UpperCamelCase__ ) parser.add_argument("""--num_workers""" , type=UpperCamelCase__ , default=0 ) SCREAMING_SNAKE_CASE__ = parser.parse_args() SCREAMING_SNAKE_CASE__ = args.streaming SCREAMING_SNAKE_CASE__ = args.num_workers SCREAMING_SNAKE_CASE__ = {"""shards""": [f'''shard_{shard_idx}''' for shard_idx in range(UpperCamelCase__ )]} SCREAMING_SNAKE_CASE__ = IterableDataset.from_generator(UpperCamelCase__ , gen_kwargs=UpperCamelCase__ ) if not streaming: SCREAMING_SNAKE_CASE__ = Dataset.from_list(list(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = split_dataset_by_node(UpperCamelCase__ , rank=UpperCamelCase__ , world_size=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = torch.utils.data.DataLoader(UpperCamelCase__ , num_workers=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = NUM_SHARDS * NUM_ITEMS_PER_SHARD SCREAMING_SNAKE_CASE__ = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) SCREAMING_SNAKE_CASE__ = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(f'''local_size {local_size} != expected_local_size {expected_local_size}''' ) if __name__ == "__main__": main()
6
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", """unet/diffusion_pytorch_model.bin""", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] self.assertTrue(is_safetensors_compatible(__A ) ) def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.bin""", """safety_checker/model.safetensors""", """vae/diffusion_pytorch_model.bin""", """vae/diffusion_pytorch_model.safetensors""", """text_encoder/pytorch_model.bin""", # Removed: 'text_encoder/model.safetensors', """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] self.assertFalse(is_safetensors_compatible(__A ) ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """unet/diffusion_pytorch_model.bin""", """unet/diffusion_pytorch_model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", """unet/diffusion_pytorch_model.fp16.bin""", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.fp16.bin""", """text_encoder/model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """text_encoder/pytorch_model.bin""", """text_encoder/model.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertTrue(is_safetensors_compatible(__A , variant=__A ) ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """safety_checker/pytorch_model.fp16.bin""", """safety_checker/model.fp16.safetensors""", """vae/diffusion_pytorch_model.fp16.bin""", """vae/diffusion_pytorch_model.fp16.safetensors""", """text_encoder/pytorch_model.fp16.bin""", # 'text_encoder/model.fp16.safetensors', """unet/diffusion_pytorch_model.fp16.bin""", """unet/diffusion_pytorch_model.fp16.safetensors""", ] SCREAMING_SNAKE_CASE__ = """fp16""" self.assertFalse(is_safetensors_compatible(__A , variant=__A ) )
6
1
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""": """Friday""", """6""": """Saturday""", } SCREAMING_SNAKE_CASE__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(UpperCamelCase__ ) < 11: raise ValueError("""Must be 10 characters long""" ) # Get month SCREAMING_SNAKE_CASE__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("""Month must be between 1 - 12""" ) SCREAMING_SNAKE_CASE__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get day SCREAMING_SNAKE_CASE__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("""Date must be between 1 - 31""" ) # Get second separator SCREAMING_SNAKE_CASE__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get year SCREAMING_SNAKE_CASE__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8_500: raise ValueError( """Year out of range. There has to be some sort of limit...right?""" ) # Get datetime obj for validation SCREAMING_SNAKE_CASE__ = datetime.date(int(UpperCamelCase__ ) , int(UpperCamelCase__ ) , int(UpperCamelCase__ ) ) # Start math if m <= 2: SCREAMING_SNAKE_CASE__ = y - 1 SCREAMING_SNAKE_CASE__ = m + 12 # maths var SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[:2] ) SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[2:] ) SCREAMING_SNAKE_CASE__ = int(2.6 * m - 5.3_9 ) SCREAMING_SNAKE_CASE__ = int(c / 4 ) SCREAMING_SNAKE_CASE__ = int(k / 4 ) SCREAMING_SNAKE_CASE__ = int(d + k ) SCREAMING_SNAKE_CASE__ = int(t + u + v + x ) SCREAMING_SNAKE_CASE__ = int(z - (2 * c) ) SCREAMING_SNAKE_CASE__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" ) # Response SCREAMING_SNAKE_CASE__ = f'''Your date {date_input}, is a {days[str(UpperCamelCase__ )]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) _lowerCamelCase = parser.parse_args() zeller(args.date_input)
6
import argparse import datetime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """Wednesday""", """4""": """Thursday""", """5""": """Friday""", """6""": """Saturday""", } SCREAMING_SNAKE_CASE__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(UpperCamelCase__ ) < 11: raise ValueError("""Must be 10 characters long""" ) # Get month SCREAMING_SNAKE_CASE__ = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("""Month must be between 1 - 12""" ) SCREAMING_SNAKE_CASE__ = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get day SCREAMING_SNAKE_CASE__ = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("""Date must be between 1 - 31""" ) # Get second separator SCREAMING_SNAKE_CASE__ = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("""Date separator must be '-' or '/'""" ) # Get year SCREAMING_SNAKE_CASE__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8_500: raise ValueError( """Year out of range. There has to be some sort of limit...right?""" ) # Get datetime obj for validation SCREAMING_SNAKE_CASE__ = datetime.date(int(UpperCamelCase__ ) , int(UpperCamelCase__ ) , int(UpperCamelCase__ ) ) # Start math if m <= 2: SCREAMING_SNAKE_CASE__ = y - 1 SCREAMING_SNAKE_CASE__ = m + 12 # maths var SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[:2] ) SCREAMING_SNAKE_CASE__ = int(str(UpperCamelCase__ )[2:] ) SCREAMING_SNAKE_CASE__ = int(2.6 * m - 5.3_9 ) SCREAMING_SNAKE_CASE__ = int(c / 4 ) SCREAMING_SNAKE_CASE__ = int(k / 4 ) SCREAMING_SNAKE_CASE__ = int(d + k ) SCREAMING_SNAKE_CASE__ = int(t + u + v + x ) SCREAMING_SNAKE_CASE__ = int(z - (2 * c) ) SCREAMING_SNAKE_CASE__ = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" ) # Response SCREAMING_SNAKE_CASE__ = f'''Your date {date_input}, is a {days[str(UpperCamelCase__ )]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) _lowerCamelCase = parser.parse_args() zeller(args.date_input)
6
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "encoder-decoder" lowerCamelCase_ = True def __init__( self :Optional[int] , **__A :str ) -> int: """simple docstring""" super().__init__(**__A ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" SCREAMING_SNAKE_CASE__ = kwargs.pop("""encoder""" ) SCREAMING_SNAKE_CASE__ = encoder_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""decoder""" ) SCREAMING_SNAKE_CASE__ = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = True @classmethod def _snake_case ( cls :str , __A :PretrainedConfig , __A :PretrainedConfig , **__A :List[str] ) -> PretrainedConfig: """simple docstring""" logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__A ) def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.encoder.to_dict() SCREAMING_SNAKE_CASE__ = self.decoder.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
6
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _lowerCamelCase = logging.getLogger(__name__) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30522, type=int) _lowerCamelCase = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: _lowerCamelCase = pickle.load(fp) logger.info('Counting occurrences for MLM.') _lowerCamelCase = Counter() for tk_ids in data: counter.update(tk_ids) _lowerCamelCase = [0] * args.vocab_size for k, v in counter.items(): _lowerCamelCase = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
6
1
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "OwlViTImageProcessor" lowerCamelCase_ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self :Optional[Any] , __A :int=None , __A :Optional[int]=None , **__A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :str , __A :Dict=None , __A :List[str]=None , __A :str=None , __A :Optional[int]="max_length" , __A :Tuple="np" , **__A :int ) -> Tuple: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(__A , __A ) or (isinstance(__A , __A ) and not isinstance(text[0] , __A )): SCREAMING_SNAKE_CASE__ = [self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )] elif isinstance(__A , __A ) and isinstance(text[0] , __A ): SCREAMING_SNAKE_CASE__ = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ = max([len(__A ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(__A ) != max_num_queries: SCREAMING_SNAKE_CASE__ = t + [""" """] * (max_num_queries - len(__A )) SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , padding=__A , return_tensors=__A , **__A ) encodings.append(__A ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = input_ids SCREAMING_SNAKE_CASE__ = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = self.image_processor( __A , return_tensors=__A , **__A ).pixel_values SCREAMING_SNAKE_CASE__ = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Dict , **__A :Dict ) -> Optional[int]: """simple docstring""" return self.image_processor.post_process(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Dict , **__A :List[str] ) -> Optional[Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*__A , **__A ) def _snake_case ( self :str , *__A :List[str] , **__A :Union[str, Any] ) -> Any: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*__A , **__A ) def _snake_case ( self :Dict , *__A :List[str] , **__A :List[str] ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Dict , *__A :Dict , **__A :List[str] ) -> str: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class @property def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __A , ) return self.image_processor
6
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
1
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = UnCLIPImageVariationPipeline lowerCamelCase_ = IMAGE_VARIATION_PARAMS - {"height", "width", "guidance_scale"} lowerCamelCase_ = IMAGE_VARIATION_BATCH_PARAMS lowerCamelCase_ = [ "generator", "return_dict", "decoder_num_inference_steps", "super_res_num_inference_steps", ] lowerCamelCase_ = False @property def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" return 32 @property def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" return 32 @property def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" return self.time_input_dim @property def _snake_case ( self :List[str] ) -> Dict: """simple docstring""" return self.time_input_dim * 4 @property def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" return 100 @property def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def _snake_case ( self :int ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__A ) @property def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(__A ) @property def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """clip_embeddings_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """cross_attention_dim""": self.cross_attention_dim, } SCREAMING_SNAKE_CASE__ = UnCLIPTextProjModel(**__A ) return model @property def _snake_case ( self :Union[str, Any] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """sample_size""": 32, # RGB in channels """in_channels""": 3, # Out channels is double in channels because predicts mean and variance """out_channels""": 6, """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, """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": """identity""", } SCREAMING_SNAKE_CASE__ = UNetaDConditionModel(**__A ) return model @property def _snake_case ( self :List[str] ) -> Dict: """simple docstring""" return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def _snake_case ( self :Tuple ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(1 ) SCREAMING_SNAKE_CASE__ = UNetaDModel(**self.dummy_super_res_kwargs ) return model def _snake_case ( self :str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dummy_decoder SCREAMING_SNAKE_CASE__ = self.dummy_text_proj SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ = self.dummy_super_res_first SCREAMING_SNAKE_CASE__ = self.dummy_super_res_last SCREAMING_SNAKE_CASE__ = UnCLIPScheduler( variance_type="""learned_range""" , prediction_type="""epsilon""" , num_train_timesteps=1000 , ) SCREAMING_SNAKE_CASE__ = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""epsilon""" , num_train_timesteps=1000 , ) SCREAMING_SNAKE_CASE__ = CLIPImageProcessor(crop_size=32 , size=32 ) SCREAMING_SNAKE_CASE__ = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def _snake_case ( self :Union[str, Any] , __A :Optional[int] , __A :List[str]=0 , __A :str=True ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A ) if str(__A ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(__A ) if pil_image: SCREAMING_SNAKE_CASE__ = input_image * 0.5 + 0.5 SCREAMING_SNAKE_CASE__ = input_image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE__ = DiffusionPipeline.numpy_to_pil(__A )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) SCREAMING_SNAKE_CASE__ = pipe(**__A ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) SCREAMING_SNAKE_CASE__ = pipe( **__A , return_dict=__A , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array( [ 0.9_9_9_7, 0.0_0_0_2, 0.9_9_9_7, 0.9_9_9_7, 0.9_9_6_9, 0.0_0_2_3, 0.9_9_9_7, 0.9_9_6_9, 0.9_9_7_0, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) SCREAMING_SNAKE_CASE__ = pipe(**__A ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) SCREAMING_SNAKE_CASE__ = pipe( **__A , return_dict=__A , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array([0.9_9_9_7, 0.0_0_0_3, 0.9_9_9_7, 0.9_9_9_7, 0.9_9_7_0, 0.0_0_2_4, 0.9_9_9_7, 0.9_9_7_1, 0.9_9_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) SCREAMING_SNAKE_CASE__ = [ pipeline_inputs["""image"""], pipeline_inputs["""image"""], ] SCREAMING_SNAKE_CASE__ = pipe(**__A ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) SCREAMING_SNAKE_CASE__ = [ tuple_pipeline_inputs["""image"""], tuple_pipeline_inputs["""image"""], ] SCREAMING_SNAKE_CASE__ = pipe( **__A , return_dict=__A , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array( [ 0.9_9_9_7, 0.9_9_8_9, 0.0_0_0_8, 0.0_0_2_1, 0.9_9_6_0, 0.0_0_1_8, 0.0_0_1_4, 0.0_0_0_2, 0.9_9_3_3, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch.device("""cpu""" ) class UpperCamelCase_ : lowerCamelCase_ = 1 SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = pipe.decoder.dtype SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) SCREAMING_SNAKE_CASE__ = pipe.prepare_latents( __A , dtype=__A , device=__A , generator=__A , latents=__A , scheduler=DummyScheduler() ) SCREAMING_SNAKE_CASE__ = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) SCREAMING_SNAKE_CASE__ = pipe.prepare_latents( __A , dtype=__A , device=__A , generator=__A , latents=__A , scheduler=DummyScheduler() ) SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) SCREAMING_SNAKE_CASE__ = pipe( **__A , decoder_latents=__A , super_res_latents=__A ).images SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A , pil_image=__A ) # Don't pass image, instead pass embedding SCREAMING_SNAKE_CASE__ = pipeline_inputs.pop("""image""" ) SCREAMING_SNAKE_CASE__ = pipe.image_encoder(__A ).image_embeds SCREAMING_SNAKE_CASE__ = pipe( **__A , decoder_latents=__A , super_res_latents=__A , image_embeddings=__A , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1E-4 @skip_mps def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch_device == """cpu""" # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor SCREAMING_SNAKE_CASE__ = 1E-2 self._test_attention_slicing_forward_pass( test_max_difference=__A , expected_max_diff=__A ) @skip_mps def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch_device == """cpu""" SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] self._test_inference_batch_single_identical( test_max_difference=__A , relax_max_difference=__A , additional_params_copy_to_batched_inputs=__A , ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes SCREAMING_SNAKE_CASE__ = [2, 3] self._test_inference_batch_consistent( batch_sizes=__A , additional_params_copy_to_batched_inputs=__A , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=__A ) @skip_mps def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" return super().test_dict_tuple_outputs_equivalent() @skip_mps def _snake_case ( self :str ) -> int: """simple docstring""" return super().test_save_load_local() @skip_mps def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" return super().test_save_load_optional_components() @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :List[str] ) -> Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png""" ) SCREAMING_SNAKE_CASE__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/unclip/karlo_v1_alpha_cat_variation_fp16.npy""" ) SCREAMING_SNAKE_CASE__ = UnCLIPImageVariationPipeline.from_pretrained( """kakaobrain/karlo-v1-alpha-image-variations""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = pipeline.to(__A ) pipeline.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = pipeline( __A , generator=__A , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(__A , __A , 15 )
6
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "OwlViTImageProcessor" lowerCamelCase_ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self :Optional[Any] , __A :int=None , __A :Optional[int]=None , **__A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :str , __A :Dict=None , __A :List[str]=None , __A :str=None , __A :Optional[int]="max_length" , __A :Tuple="np" , **__A :int ) -> Tuple: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(__A , __A ) or (isinstance(__A , __A ) and not isinstance(text[0] , __A )): SCREAMING_SNAKE_CASE__ = [self.tokenizer(__A , padding=__A , return_tensors=__A , **__A )] elif isinstance(__A , __A ) and isinstance(text[0] , __A ): SCREAMING_SNAKE_CASE__ = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ = max([len(__A ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(__A ) != max_num_queries: SCREAMING_SNAKE_CASE__ = t + [""" """] * (max_num_queries - len(__A )) SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , padding=__A , return_tensors=__A , **__A ) encodings.append(__A ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = input_ids SCREAMING_SNAKE_CASE__ = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ = BatchEncoding() SCREAMING_SNAKE_CASE__ = self.image_processor( __A , return_tensors=__A , **__A ).pixel_values SCREAMING_SNAKE_CASE__ = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Dict , **__A :Dict ) -> Optional[int]: """simple docstring""" return self.image_processor.post_process(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Dict , **__A :List[str] ) -> Optional[Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*__A , **__A ) def _snake_case ( self :str , *__A :List[str] , **__A :Union[str, Any] ) -> Any: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*__A , **__A ) def _snake_case ( self :Dict , *__A :List[str] , **__A :List[str] ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Dict , *__A :Dict , **__A :List[str] ) -> str: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class @property def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __A , ) return self.image_processor
6
1
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor _lowerCamelCase = random.Random() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any]=1.0 , UpperCamelCase__: str=None , UpperCamelCase__: int=None ): if rng is None: SCREAMING_SNAKE_CASE__ = global_rng SCREAMING_SNAKE_CASE__ = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class UpperCamelCase_ ( unittest.TestCase ): def __init__( self :Optional[Any] , __A :str , __A :int=7 , __A :Optional[Any]=400 , __A :Tuple=2000 , __A :Any=24 , __A :Optional[Any]=24 , __A :List[str]=0.0 , __A :Optional[int]=1_6000 , __A :Dict=True , __A :List[Any]=True , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = min_seq_length SCREAMING_SNAKE_CASE__ = max_seq_length SCREAMING_SNAKE_CASE__ = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ = feature_size SCREAMING_SNAKE_CASE__ = num_mel_bins SCREAMING_SNAKE_CASE__ = padding_value SCREAMING_SNAKE_CASE__ = sampling_rate SCREAMING_SNAKE_CASE__ = return_attention_mask SCREAMING_SNAKE_CASE__ = do_normalize def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _snake_case ( self :List[str] , __A :str=False , __A :Any=False ) -> Any: """simple docstring""" def _flatten(__A :Tuple ): return list(itertools.chain(*__A ) ) if equal_length: SCREAMING_SNAKE_CASE__ = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ = [np.asarray(__A ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = SpeechaTextFeatureExtractor if is_speech_available() else None def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = SpeechaTextFeatureExtractionTester(self ) def _snake_case ( self :Dict , __A :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" self.assertTrue(np.all(np.mean(__A , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__A , axis=0 ) - 1 ) < 1E-3 ) ) def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ = [np.asarray(__A ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ = feature_extractor(__A , padding=__A , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input SCREAMING_SNAKE_CASE__ = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features SCREAMING_SNAKE_CASE__ = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(__A , __A , atol=1E-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ = feature_extractor(__A , return_tensors="""np""" ).input_features SCREAMING_SNAKE_CASE__ = feature_extractor(__A , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__A , __A ): self.assertTrue(np.allclose(__A , __A , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ = np.asarray(__A ) SCREAMING_SNAKE_CASE__ = feature_extractor(__A , return_tensors="""np""" ).input_features SCREAMING_SNAKE_CASE__ = feature_extractor(__A , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(__A , __A ): self.assertTrue(np.allclose(__A , __A , atol=1E-3 ) ) def _snake_case ( self :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ = ["""longest""", """max_length""", """do_not_pad"""] SCREAMING_SNAKE_CASE__ = [None, 16, None] for max_length, padding in zip(__A , __A ): SCREAMING_SNAKE_CASE__ = feature_extractor( __A , padding=__A , max_length=__A , return_attention_mask=__A ) SCREAMING_SNAKE_CASE__ = inputs.input_features SCREAMING_SNAKE_CASE__ = inputs.attention_mask SCREAMING_SNAKE_CASE__ = [np.sum(__A ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def _snake_case ( self :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ = ["""longest""", """max_length""", """do_not_pad"""] SCREAMING_SNAKE_CASE__ = [None, 16, None] for max_length, padding in zip(__A , __A ): SCREAMING_SNAKE_CASE__ = feature_extractor( __A , max_length=__A , padding=__A , return_tensors="""np""" , return_attention_mask=__A ) SCREAMING_SNAKE_CASE__ = inputs.input_features SCREAMING_SNAKE_CASE__ = inputs.attention_mask SCREAMING_SNAKE_CASE__ = [np.sum(__A ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def _snake_case ( self :Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ = feature_extractor( __A , padding="""max_length""" , max_length=4 , truncation=__A , return_tensors="""np""" , return_attention_mask=__A , ) SCREAMING_SNAKE_CASE__ = inputs.input_features SCREAMING_SNAKE_CASE__ = inputs.attention_mask SCREAMING_SNAKE_CASE__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ = feature_extractor( __A , padding="""longest""" , max_length=4 , truncation=__A , return_tensors="""np""" , return_attention_mask=__A , ) SCREAMING_SNAKE_CASE__ = inputs.input_features SCREAMING_SNAKE_CASE__ = inputs.attention_mask SCREAMING_SNAKE_CASE__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 24) ) SCREAMING_SNAKE_CASE__ = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ = feature_extractor( __A , padding="""longest""" , max_length=16 , truncation=__A , return_tensors="""np""" , return_attention_mask=__A , ) SCREAMING_SNAKE_CASE__ = inputs.input_features SCREAMING_SNAKE_CASE__ = inputs.attention_mask SCREAMING_SNAKE_CASE__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 24) ) def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ = np.random.rand(100 , 32 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _snake_case ( self :Union[str, Any] , __A :Union[str, Any] ) -> Tuple: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ = ds.sort("""id""" ).select(range(__A ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = np.array([ -1.5_7_4_5, -1.7_7_1_3, -1.7_0_2_0, -1.6_0_6_9, -1.2_2_5_0, -1.1_1_0_5, -0.9_0_7_2, -0.8_2_4_1, -1.2_3_1_0, -0.8_0_9_8, -0.3_3_2_0, -0.4_1_0_1, -0.7_9_8_5, -0.4_9_9_6, -0.8_2_1_3, -0.9_1_2_8, -1.0_4_2_0, -1.1_2_8_6, -1.0_4_4_0, -0.7_9_9_9, -0.8_4_0_5, -1.2_2_7_5, -1.5_4_4_3, -1.4_6_2_5, ] ) # fmt: on SCREAMING_SNAKE_CASE__ = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ = feature_extractor(__A , return_tensors="""pt""" ).input_features self.assertEquals(input_features.shape , (1, 584, 24) ) self.assertTrue(np.allclose(input_features[0, 0, :30] , __A , atol=1E-4 ) )
6
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self :Union[str, Any] , __A :int = 3 , __A :int = 3 , __A :Tuple[str] = ("DownEncoderBlock2D",) , __A :Tuple[str] = ("UpDecoderBlock2D",) , __A :Tuple[int] = (64,) , __A :int = 1 , __A :str = "silu" , __A :int = 3 , __A :int = 32 , __A :int = 256 , __A :int = 32 , __A :Optional[int] = None , __A :float = 0.1_8_2_1_5 , __A :str = "group" , ) -> Any: """simple docstring""" super().__init__() # pass init params to Encoder SCREAMING_SNAKE_CASE__ = Encoder( in_channels=__A , out_channels=__A , down_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , double_z=__A , ) SCREAMING_SNAKE_CASE__ = vq_embed_dim if vq_embed_dim is not None else latent_channels SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) SCREAMING_SNAKE_CASE__ = VectorQuantizer(__A , __A , beta=0.2_5 , remap=__A , sane_index_shape=__A ) SCREAMING_SNAKE_CASE__ = nn.Convad(__A , __A , 1 ) # pass init params to Decoder SCREAMING_SNAKE_CASE__ = Decoder( in_channels=__A , out_channels=__A , up_block_types=__A , block_out_channels=__A , layers_per_block=__A , act_fn=__A , norm_num_groups=__A , norm_type=__A , ) @apply_forward_hook def _snake_case ( self :Union[str, Any] , __A :torch.FloatTensor , __A :bool = True ) -> VQEncoderOutput: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.encoder(__A ) SCREAMING_SNAKE_CASE__ = self.quant_conv(__A ) if not return_dict: return (h,) return VQEncoderOutput(latents=__A ) @apply_forward_hook def _snake_case ( self :Tuple , __A :torch.FloatTensor , __A :bool = False , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" if not force_not_quantize: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = h SCREAMING_SNAKE_CASE__ = self.post_quant_conv(__A ) SCREAMING_SNAKE_CASE__ = self.decoder(__A , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=__A ) def _snake_case ( self :int , __A :torch.FloatTensor , __A :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample SCREAMING_SNAKE_CASE__ = self.encode(__A ).latents SCREAMING_SNAKE_CASE__ = self.decode(__A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__A )
6
1
def SCREAMING_SNAKE_CASE__ ( ): return [list(range(1_000 - i , -1_000 - i , -1 ) ) for i in range(1_000 )] _lowerCamelCase = generate_large_matrix() _lowerCamelCase = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ): assert all(row == sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ) for row in grid ) assert all(list(UpperCamelCase__ ) == sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ) for col in zip(*UpperCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: SCREAMING_SNAKE_CASE__ = (left + right) // 2 SCREAMING_SNAKE_CASE__ = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: SCREAMING_SNAKE_CASE__ = mid + 1 else: SCREAMING_SNAKE_CASE__ = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ): SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = len(grid[0] ) for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = find_negative_index(grid[i][:bound] ) total += bound return (len(UpperCamelCase__ ) * len(grid[0] )) - total def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ): return len([number for row in grid for number in row if number < 0] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ): SCREAMING_SNAKE_CASE__ = 0 for row in grid: for i, number in enumerate(UpperCamelCase__ ): if number < 0: total += len(UpperCamelCase__ ) - i break return total def SCREAMING_SNAKE_CASE__ ( ): from timeit import timeit print("""Running benchmarks""" ) SCREAMING_SNAKE_CASE__ = ( """from __main__ import count_negatives_binary_search, """ """count_negatives_brute_force, count_negatives_brute_force_with_break, grid""" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): SCREAMING_SNAKE_CASE__ = timeit(f'''{func}(grid=grid)''' , setup=UpperCamelCase__ , number=500 ) print(f'''{func}() took {time:0.4f} seconds''' ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
6
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = jnp.floataa lowerCamelCase_ = True def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = nn.Dense(5 , dtype=self.dtype ) def __call__( self :List[Any] , *__A :int , **__A :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super().__call__(*__A , **__A ) SCREAMING_SNAKE_CASE__ = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = FlaxBigBirdForNaturalQuestionsModule def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple ): def cross_entropy(UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=None ): SCREAMING_SNAKE_CASE__ = logits.shape[-1] SCREAMING_SNAKE_CASE__ = (labels[..., None] == jnp.arange(UpperCamelCase__ )[None]).astype("""f4""" ) SCREAMING_SNAKE_CASE__ = jax.nn.log_softmax(UpperCamelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE__ = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: SCREAMING_SNAKE_CASE__ = reduction(UpperCamelCase__ ) return loss SCREAMING_SNAKE_CASE__ = partial(UpperCamelCase__ , reduction=jnp.mean ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cross_entropy(UpperCamelCase__ , UpperCamelCase__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class UpperCamelCase_ : lowerCamelCase_ = "google/bigbird-roberta-base" lowerCamelCase_ = 30_00 lowerCamelCase_ = 1_05_00 lowerCamelCase_ = 1_28 lowerCamelCase_ = 3 lowerCamelCase_ = 1 lowerCamelCase_ = 5 # tx_args lowerCamelCase_ = 3e-5 lowerCamelCase_ = 0.0 lowerCamelCase_ = 2_00_00 lowerCamelCase_ = 0.0095 lowerCamelCase_ = "bigbird-roberta-natural-questions" lowerCamelCase_ = "training-expt" lowerCamelCase_ = "data/nq-training.jsonl" lowerCamelCase_ = "data/nq-validation.jsonl" def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(self.base_dir , self.save_dir ) SCREAMING_SNAKE_CASE__ = self.batch_size_per_device * jax.device_count() @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 40_96 # no dynamic padding on TPUs def __call__( self :Optional[Any] , __A :Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.collate_fn(__A ) SCREAMING_SNAKE_CASE__ = jax.tree_util.tree_map(__A , __A ) return batch def _snake_case ( self :List[Any] , __A :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.fetch_inputs(features["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = { """input_ids""": jnp.array(__A , dtype=jnp.intaa ), """attention_mask""": jnp.array(__A , dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] , dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] , dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] , dtype=jnp.intaa ), } return batch def _snake_case ( self :Tuple , __A :list ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self._fetch_inputs(__A ) for ids in input_ids] return zip(*__A ) def _snake_case ( self :List[str] , __A :list ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [1 for _ in range(len(__A ) )] while len(__A ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=None ): if seed is not None: SCREAMING_SNAKE_CASE__ = dataset.shuffle(seed=UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) // batch_size ): SCREAMING_SNAKE_CASE__ = dataset[i * batch_size : (i + 1) * batch_size] yield dict(UpperCamelCase__ ) @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[int] , **UpperCamelCase__: Optional[int] ): def loss_fn(UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=UpperCamelCase__ , dropout_rng=UpperCamelCase__ , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs return state.loss_fn( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = jax.random.split(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.value_and_grad(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = grad_fn(state.params ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean(UpperCamelCase__ , """batch""" ) SCREAMING_SNAKE_CASE__ = state.apply_gradients(grads=UpperCamelCase__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , **UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = model_inputs.pop("""start_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""end_labels""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""pooled_labels""" ) SCREAMING_SNAKE_CASE__ = state.apply_fn(**UpperCamelCase__ , params=state.params , train=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs SCREAMING_SNAKE_CASE__ = state.loss_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class UpperCamelCase_ ( train_state.TrainState ): lowerCamelCase_ = struct.field(pytree_node=UpperCamelCase__ ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None def _snake_case ( self :List[Any] , __A :str , __A :str , __A :str , __A :Tuple=None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = model.params SCREAMING_SNAKE_CASE__ = TrainState.create( apply_fn=model.__call__ , params=__A , tx=__A , loss_fn=__A , ) if ckpt_dir is not None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = restore_checkpoint(__A , __A ) SCREAMING_SNAKE_CASE__ = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = build_tx(**__A ) SCREAMING_SNAKE_CASE__ = train_state.TrainState( step=__A , apply_fn=model.__call__ , params=__A , tx=__A , opt_state=__A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = data_collator SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = jax_utils.replicate(__A ) return state def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :int , __A :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.args SCREAMING_SNAKE_CASE__ = len(__A ) // args.batch_size SCREAMING_SNAKE_CASE__ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ = jax.random.split(__A , jax.device_count() ) for epoch in range(args.max_epochs ): SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , args.batch_size , seed=__A ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc=f'''Running EPOCH-{epoch}''' ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.train_step_fn(__A , __A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(state.step ) SCREAMING_SNAKE_CASE__ = running_loss.item() / i SCREAMING_SNAKE_CASE__ = self.scheduler_fn(state_step - 1 ) SCREAMING_SNAKE_CASE__ = self.evaluate(__A , __A ) SCREAMING_SNAKE_CASE__ = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(__A ) ) self.logger.log(__A , commit=__A ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__A ) def _snake_case ( self :List[str] , __A :Dict , __A :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = get_batched_dataset(__A , self.args.batch_size ) SCREAMING_SNAKE_CASE__ = len(__A ) // self.args.batch_size SCREAMING_SNAKE_CASE__ = jnp.array(0 , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ = 0 for batch in tqdm(__A , total=__A , desc="""Evaluating ... """ ): SCREAMING_SNAKE_CASE__ = self.data_collator(__A ) SCREAMING_SNAKE_CASE__ = self.val_step_fn(__A , **__A ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _snake_case ( self :List[Any] , __A :Any , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = jax_utils.unreplicate(__A ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=""" ... """ ) self.model_save_fn(__A , params=state.params ) with open(os.path.join(__A , """opt_state.msgpack""" ) , """wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__A , """args.joblib""" ) ) joblib.dump(self.data_collator , os.path.join(__A , """data_collator.joblib""" ) ) with open(os.path.join(__A , """training_state.json""" ) , """w""" ) as f: json.dump({"""step""": state.step.item()} , __A ) print("""DONE""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Optional[Any] ): print(f'''RESTORING CHECKPOINT FROM {save_dir}''' , end=""" ... """ ) with open(os.path.join(UpperCamelCase__ , """flax_model.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.params , f.read() ) with open(os.path.join(UpperCamelCase__ , """opt_state.msgpack""" ) , """rb""" ) as f: SCREAMING_SNAKE_CASE__ = from_bytes(state.opt_state , f.read() ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """args.joblib""" ) ) SCREAMING_SNAKE_CASE__ = joblib.load(os.path.join(UpperCamelCase__ , """data_collator.joblib""" ) ) with open(os.path.join(UpperCamelCase__ , """training_state.json""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.load(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = num_train_steps - warmup_steps SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=UpperCamelCase__ , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.linear_schedule(init_value=UpperCamelCase__ , end_value=1e-7 , transition_steps=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): def weight_decay_mask(UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = traverse_util.flatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = scheduler_fn(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = optax.adamw(learning_rate=UpperCamelCase__ , weight_decay=UpperCamelCase__ , mask=UpperCamelCase__ ) return tx, lr
6
1