code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import os def _lowerCamelCase ( ): with open(os.path.dirname(__a ) + '''/p022_names.txt''' ) as file: SCREAMING_SNAKE_CASE_ = str(file.readlines()[0] ) SCREAMING_SNAKE_CASE_ = names.replace('''"''', '''''' ).split(''',''' ) names.sort() SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 for i, name in enumerate(__a ): for letter in name: name_score += ord(__a ) - 64 total_score += (i + 1) * name_score SCREAMING_SNAKE_CASE_ = 0 return total_score if __name__ == "__main__": print(solution())
628
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = TransfoXLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''<unk> UNwanted , running''' SCREAMING_SNAKE_CASE_ = '''<unk> unwanted, running''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [0, 4, 8, 7] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' SCREAMING_SNAKE_CASE_ = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = len(SCREAMING_SNAKE_CASE_ ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
628
1
"""simple docstring""" from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class snake_case ( __lowercase ): UpperCAmelCase__ = ['''image_processor''', '''tokenizer'''] UpperCAmelCase__ = '''BridgeTowerImageProcessor''' UpperCAmelCase__ = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.tokenizer( text=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , stride=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_overflowing_tokens=SCREAMING_SNAKE_CASE_ , return_special_tokens_mask=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , return_length=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # add pixel_values + pixel_mask SCREAMING_SNAKE_CASE_ = self.image_processor( SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , do_normalize=SCREAMING_SNAKE_CASE_ , do_center_crop=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) encoding.update(SCREAMING_SNAKE_CASE_ ) return encoding def _lowercase (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def _lowercase (self ): """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 ) )
628
"""simple docstring""" from __future__ import annotations import typing from collections import Counter def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__a, max_perimeter + 1 ): SCREAMING_SNAKE_CASE_ = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__a ): SCREAMING_SNAKE_CASE_ = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _lowerCamelCase ( __a = 1_000 ): SCREAMING_SNAKE_CASE_ = pythagorean_triple(__a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
628
1
"""simple docstring""" 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 _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = SwinConfig.from_pretrained( '''microsoft/swin-tiny-patch4-window7-224''', out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ) SCREAMING_SNAKE_CASE_ = MaskFormerConfig(backbone_config=__a ) 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(__a, __a, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(__a ): v for k, v in idalabel.items()} return config def _lowerCamelCase ( __a ): 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 _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = dct.pop(__a ) SCREAMING_SNAKE_CASE_ = val def _lowerCamelCase ( __a, __a ): 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 _lowerCamelCase ( __a, __a ): # 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 _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__a, stream=__a ).raw ) return im @torch.no_grad() def _lowerCamelCase ( __a, __a, __a, __a = False ): SCREAMING_SNAKE_CASE_ = get_maskformer_config(__a ) # load original state_dict with open(__a, '''rb''' ) as f: SCREAMING_SNAKE_CASE_ = pickle.load(__a ) SCREAMING_SNAKE_CASE_ = data['''model'''] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys SCREAMING_SNAKE_CASE_ = create_rename_keys(__a ) for src, dest in rename_keys: rename_key(__a, __a, __a ) read_in_swin_q_k_v(__a, config.backbone_config ) read_in_decoder_q_k_v(__a, __a ) # update to torch tensors for key, value in state_dict.items(): SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) # load 🤗 model SCREAMING_SNAKE_CASE_ = MaskFormerForInstanceSegmentation(__a ) model.eval() for name, param in model.named_parameters(): print(__a, param.shape ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = model.load_state_dict(__a, strict=__a ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(__a ) == 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=__a, reduce_labels=__a ) SCREAMING_SNAKE_CASE_ = image_processor(__a, return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = model(**__a ) 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], __a, 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(__a ).mkdir(exist_ok=__a ) model.save_pretrained(__a ) image_processor.save_pretrained(__a ) 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 )
628
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _lowerCamelCase ( __a ): if is_torch_version('''<''', '''2.0.0''' ) or not hasattr(__a, '''_dynamo''' ): return False return isinstance(__a, torch._dynamo.eval_frame.OptimizedModule ) def _lowerCamelCase ( __a, __a = True ): SCREAMING_SNAKE_CASE_ = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE_ = is_compiled_module(__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE_ = getattr(__a, '''forward''' ) SCREAMING_SNAKE_CASE_ = model.__dict__.pop('''_original_forward''', __a ) if original_forward is not None: while hasattr(__a, '''__wrapped__''' ): SCREAMING_SNAKE_CASE_ = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE_ = forward if getattr(__a, '''_converted_to_transformer_engine''', __a ): convert_model(__a, to_transformer_engine=__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = compiled_model return model def _lowerCamelCase ( ): PartialState().wait_for_everyone() def _lowerCamelCase ( __a, __a ): if PartialState().distributed_type == DistributedType.TPU: xm.save(__a, __a ) elif PartialState().local_process_index == 0: torch.save(__a, __a ) @contextmanager def _lowerCamelCase ( **__a ): for key, value in kwargs.items(): SCREAMING_SNAKE_CASE_ = str(__a ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _lowerCamelCase ( __a ): if not hasattr(__a, '''__qualname__''' ) and not hasattr(__a, '''__name__''' ): SCREAMING_SNAKE_CASE_ = getattr(__a, '''__class__''', __a ) if hasattr(__a, '''__qualname__''' ): return obj.__qualname__ if hasattr(__a, '''__name__''' ): return obj.__name__ return str(__a ) def _lowerCamelCase ( __a, __a ): for key, value in source.items(): if isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = destination.setdefault(__a, {} ) merge_dicts(__a, __a ) else: SCREAMING_SNAKE_CASE_ = value return destination def _lowerCamelCase ( __a = None ): if port is None: SCREAMING_SNAKE_CASE_ = 29_500 with socket.socket(socket.AF_INET, socket.SOCK_STREAM ) as s: return s.connect_ex(('''localhost''', port) ) == 0
628
1
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a, __a, __a ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file SCREAMING_SNAKE_CASE_ = TapasConfig.from_json_file(__a ) # set absolute/relative position embeddings parameter SCREAMING_SNAKE_CASE_ = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": SCREAMING_SNAKE_CASE_ = TapasForQuestionAnswering(config=__a ) elif task == "WTQ": # run_task_main.py hparams SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = True # hparam_utils.py hparams SCREAMING_SNAKE_CASE_ = 0.6_6_4_6_9_4 SCREAMING_SNAKE_CASE_ = 0.2_0_7_9_5_1 SCREAMING_SNAKE_CASE_ = 0.1_2_1_1_9_4 SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = 0.0_3_5_2_5_1_3 SCREAMING_SNAKE_CASE_ = TapasForQuestionAnswering(config=__a ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = False # hparam_utils.py hparams SCREAMING_SNAKE_CASE_ = 3_6.4_5_1_9 SCREAMING_SNAKE_CASE_ = 0.9_0_3_4_2_1 SCREAMING_SNAKE_CASE_ = 2_2_2.0_8_8 SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = 0.7_6_3_1_4_1 SCREAMING_SNAKE_CASE_ = TapasForQuestionAnswering(config=__a ) elif task == "TABFACT": SCREAMING_SNAKE_CASE_ = TapasForSequenceClassification(config=__a ) elif task == "MLM": SCREAMING_SNAKE_CASE_ = TapasForMaskedLM(config=__a ) elif task == "INTERMEDIATE_PRETRAINING": SCREAMING_SNAKE_CASE_ = TapasModel(config=__a ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__a, __a, __a ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) SCREAMING_SNAKE_CASE_ = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''', model_max_length=512 ) tokenizer.save_pretrained(__a ) print('''Used relative position embeddings:''', model.config.reset_position_index_per_cell ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
628
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = CTRLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE_ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
628
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'tiiuae/falcon-40b': 'https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json', 'tiiuae/falcon-7b': 'https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json', } class snake_case ( __lowercase ): UpperCAmelCase__ = '''falcon''' UpperCAmelCase__ = ['''past_key_values'''] def __init__(self , SCREAMING_SNAKE_CASE_=6_50_24 , SCREAMING_SNAKE_CASE_=45_44 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=71 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=11 , SCREAMING_SNAKE_CASE_=11 , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = vocab_size # Backward compatibility with n_embed kwarg SCREAMING_SNAKE_CASE_ = kwargs.pop('''n_embed''' , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = hidden_size if n_embed is None else n_embed SCREAMING_SNAKE_CASE_ = num_hidden_layers SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = layer_norm_epsilon SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = use_cache SCREAMING_SNAKE_CASE_ = hidden_dropout SCREAMING_SNAKE_CASE_ = attention_dropout SCREAMING_SNAKE_CASE_ = bos_token_id SCREAMING_SNAKE_CASE_ = eos_token_id SCREAMING_SNAKE_CASE_ = num_attention_heads if num_kv_heads is None else num_kv_heads SCREAMING_SNAKE_CASE_ = alibi SCREAMING_SNAKE_CASE_ = new_decoder_architecture SCREAMING_SNAKE_CASE_ = multi_query # Ignored when new_decoder_architecture is True SCREAMING_SNAKE_CASE_ = parallel_attn SCREAMING_SNAKE_CASE_ = bias super().__init__(bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def _lowercase (self ): """simple docstring""" return self.hidden_size // self.num_attention_heads @property def _lowercase (self ): """simple docstring""" return not self.alibi
628
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a, __a ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_ = BigBirdConfig.from_json_file(__a ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: SCREAMING_SNAKE_CASE_ = BigBirdForQuestionAnswering(__a ) else: SCREAMING_SNAKE_CASE_ = BigBirdForPreTraining(__a ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__a, __a, is_trivia_qa=__a ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) 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( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
628
1
"""simple docstring""" # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler') class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = False ): """simple docstring""" SCREAMING_SNAKE_CASE_ = scheduler SCREAMING_SNAKE_CASE_ = optimizers if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) else [optimizers] SCREAMING_SNAKE_CASE_ = split_batches SCREAMING_SNAKE_CASE_ = step_with_optimizer SCREAMING_SNAKE_CASE_ = GradientState() def _lowercase (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step SCREAMING_SNAKE_CASE_ = AcceleratorState().num_processes for _ in range(SCREAMING_SNAKE_CASE_ ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , '''total_steps''' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) else: self.scheduler.step(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" return self.scheduler.get_last_lr() def _lowercase (self ): """simple docstring""" return self.scheduler.state_dict() def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self.scheduler.load_state_dict(SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" return self.scheduler.get_lr() def _lowercase (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.scheduler.print_lr(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
628
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name def _lowerCamelCase ( __a ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''', __a, ) if isinstance(__a, torch.Tensor ): return image elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [image] if isinstance(image[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = image[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE_ = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = np.array(__a ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = image.transpose(0, 3, 1, 2 ) SCREAMING_SNAKE_CASE_ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(image[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return image def _lowerCamelCase ( __a ): if isinstance(__a, torch.Tensor ): return mask elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [mask] if isinstance(mask[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = mask[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE_ = [np.array(m.convert('''L''' ).resize((w, h), resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(mask[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return mask class snake_case ( __lowercase ): UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 2_50 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = image SCREAMING_SNAKE_CASE_ = _preprocess_image(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = _preprocess_mask(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE_ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) SCREAMING_SNAKE_CASE_ = original_image.shape SCREAMING_SNAKE_CASE_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) SCREAMING_SNAKE_CASE_ = eta SCREAMING_SNAKE_CASE_ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE_ = generator[0] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE_ = self.scheduler.undo_step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = t SCREAMING_SNAKE_CASE_ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
628
1
"""simple docstring""" from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def _lowerCamelCase ( __a ): return {key.lstrip('''-''' ): value for key, value in zip(unknown_args[::2], unknown_args[1::2] )} def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = ArgumentParser( '''HuggingFace Datasets CLI tool''', usage='''datasets-cli <command> [<args>]''', allow_abbrev=__a ) SCREAMING_SNAKE_CASE_ = parser.add_subparsers(help='''datasets-cli command helpers''' ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(__a ) EnvironmentCommand.register_subcommand(__a ) TestCommand.register_subcommand(__a ) RunBeamCommand.register_subcommand(__a ) DummyDataCommand.register_subcommand(__a ) # Parse args SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = parser.parse_known_args() if not hasattr(__a, '''func''' ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE_ = parse_unknown_args(__a ) # Run SCREAMING_SNAKE_CASE_ = args.func(__a, **__a ) service.run() if __name__ == "__main__": main()
628
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a, __a ): return (preds == labels).mean() @dataclass class snake_case : UpperCAmelCase__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class snake_case : UpperCAmelCase__ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) UpperCAmelCase__ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) UpperCAmelCase__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def _lowerCamelCase ( ): # 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() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1 ), training_args.fpaa, ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''', __a ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE_ = processors[data_args.task_name]() SCREAMING_SNAKE_CASE_ = processor.get_labels() SCREAMING_SNAKE_CASE_ = len(__a ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=__a, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=__a, cache_dir=model_args.cache_dir, ) # Get datasets SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, ) if training_args.do_eval else None ) def compute_metrics(__a ) -> Dict: SCREAMING_SNAKE_CASE_ = np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(__a, p.label_ids )} # Data collator SCREAMING_SNAKE_CASE_ = DataCollatorWithPadding(__a, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE_ = Trainer( model=__a, args=__a, train_dataset=__a, eval_dataset=__a, compute_metrics=__a, data_collator=__a, ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ = trainer.evaluate() SCREAMING_SNAKE_CASE_ = os.path.join(training_args.output_dir, '''eval_results.txt''' ) if trainer.is_world_master(): with open(__a, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''', __a, __a ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__a ) return results def _lowerCamelCase ( __a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
628
1
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json', 'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json', 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json', 'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json', 'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json', 'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json', 'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json', 'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json', 'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json', 'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json', 'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json', 'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json', } class snake_case ( __lowercase ): UpperCAmelCase__ = '''codegen''' UpperCAmelCase__ = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__(self , SCREAMING_SNAKE_CASE_=5_04_00 , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=40_96 , SCREAMING_SNAKE_CASE_=28 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="gelu_new" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=5_02_56 , SCREAMING_SNAKE_CASE_=5_02_56 , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = vocab_size SCREAMING_SNAKE_CASE_ = n_ctx 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_ = rotary_dim 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_ = use_cache SCREAMING_SNAKE_CASE_ = bos_token_id SCREAMING_SNAKE_CASE_ = eos_token_id super().__init__( bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "default" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , ): """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE_ , task=SCREAMING_SNAKE_CASE_ , patching_specs=SCREAMING_SNAKE_CASE_ , use_past=SCREAMING_SNAKE_CASE_ ) if not getattr(self._config , '''pad_token_id''' , SCREAMING_SNAKE_CASE_ ): # TODO: how to do that better? SCREAMING_SNAKE_CASE_ = 0 @property def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_ , direction='''inputs''' ) SCREAMING_SNAKE_CASE_ = {0: '''batch''', 1: '''past_sequence + sequence'''} else: SCREAMING_SNAKE_CASE_ = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def _lowercase (self ): """simple docstring""" return self._config.n_layer @property def _lowercase (self ): """simple docstring""" return self._config.n_head def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = super(SCREAMING_SNAKE_CASE_ , self ).generate_dummy_inputs( SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ , seq_length=SCREAMING_SNAKE_CASE_ , is_pair=SCREAMING_SNAKE_CASE_ , framework=SCREAMING_SNAKE_CASE_ ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE_ = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE_ = seqlen + 2 SCREAMING_SNAKE_CASE_ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE_ = [ (torch.zeros(SCREAMING_SNAKE_CASE_ ), torch.zeros(SCREAMING_SNAKE_CASE_ )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE_ = common_inputs['''attention_mask'''] if self.use_past: SCREAMING_SNAKE_CASE_ = ordered_inputs['''attention_mask'''].dtype SCREAMING_SNAKE_CASE_ = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )] , dim=1 ) return ordered_inputs @property def _lowercase (self ): """simple docstring""" return 13
628
"""simple docstring""" import cva import numpy as np class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if k in (0.04, 0.06): SCREAMING_SNAKE_CASE_ = k SCREAMING_SNAKE_CASE_ = window_size else: raise ValueError('''invalid k value''' ) def __str__(self ): """simple docstring""" return str(self.k ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = cva.imread(SCREAMING_SNAKE_CASE_ , 0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = img.shape SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = img.copy() SCREAMING_SNAKE_CASE_ = cva.cvtColor(SCREAMING_SNAKE_CASE_ , cva.COLOR_GRAY2RGB ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = np.gradient(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = dx**2 SCREAMING_SNAKE_CASE_ = dy**2 SCREAMING_SNAKE_CASE_ = dx * dy SCREAMING_SNAKE_CASE_ = 0.04 SCREAMING_SNAKE_CASE_ = self.window_size // 2 for y in range(SCREAMING_SNAKE_CASE_ , h - offset ): for x in range(SCREAMING_SNAKE_CASE_ , w - offset ): SCREAMING_SNAKE_CASE_ = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = (wxx * wyy) - (wxy**2) SCREAMING_SNAKE_CASE_ = wxx + wyy SCREAMING_SNAKE_CASE_ = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": lowerCAmelCase__ = HarrisCorner(0.04, 3) lowerCAmelCase__, lowerCAmelCase__ = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
628
1
"""simple docstring""" from typing import Any class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = data SCREAMING_SNAKE_CASE_ = None def __repr__(self ): """simple docstring""" return f'Node({self.data})' class snake_case : def __init__(self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None def __iter__(self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.head while node: yield node.data SCREAMING_SNAKE_CASE_ = node.next def __len__(self ): """simple docstring""" return sum(1 for _ in self ) def __repr__(self ): """simple docstring""" return "->".join([str(SCREAMING_SNAKE_CASE_ ) for item in self] ) def __getitem__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if not 0 <= index < len(self ): raise ValueError('''list index out of range.''' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if not 0 <= index < len(self ): raise ValueError('''list index out of range.''' ) SCREAMING_SNAKE_CASE_ = self.head for _ in range(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = current.next SCREAMING_SNAKE_CASE_ = data def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self.insert_nth(len(self ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self.insert_nth(0 , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if not 0 <= index <= len(self ): raise IndexError('''list index out of range''' ) SCREAMING_SNAKE_CASE_ = Node(SCREAMING_SNAKE_CASE_ ) if self.head is None: SCREAMING_SNAKE_CASE_ = new_node elif index == 0: SCREAMING_SNAKE_CASE_ = self.head # link new_node to head SCREAMING_SNAKE_CASE_ = new_node else: SCREAMING_SNAKE_CASE_ = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE_ = temp.next SCREAMING_SNAKE_CASE_ = temp.next SCREAMING_SNAKE_CASE_ = new_node def _lowercase (self ): # print every node data """simple docstring""" print(self ) def _lowercase (self ): """simple docstring""" return self.delete_nth(0 ) def _lowercase (self ): # delete from tail """simple docstring""" return self.delete_nth(len(self ) - 1 ) def _lowercase (self , SCREAMING_SNAKE_CASE_ = 0 ): """simple docstring""" if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('''List index out of range.''' ) SCREAMING_SNAKE_CASE_ = self.head # default first node if index == 0: SCREAMING_SNAKE_CASE_ = self.head.next else: SCREAMING_SNAKE_CASE_ = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE_ = temp.next SCREAMING_SNAKE_CASE_ = temp.next SCREAMING_SNAKE_CASE_ = temp.next.next return delete_node.data def _lowercase (self ): """simple docstring""" return self.head is None def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = self.head while current: # Store the current node's next node. SCREAMING_SNAKE_CASE_ = current.next # Make the current node's next point backwards SCREAMING_SNAKE_CASE_ = prev # Make the previous node be the current node SCREAMING_SNAKE_CASE_ = current # Make the current node the next node (to progress iteration) SCREAMING_SNAKE_CASE_ = next_node # Return prev in order to put the head at the end SCREAMING_SNAKE_CASE_ = prev def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = LinkedList() assert linked_list.is_empty() is True assert str(__a ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(__a ) == i linked_list.insert_nth(__a, i + 1 ) assert str(__a ) == "->".join(str(__a ) for i in range(1, 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(__a ) == "->".join(str(__a ) for i in range(0, 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(__a ) == 9 assert str(__a ) == "->".join(str(__a ) for i in range(1, 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0, 9 ) ) is True for i in range(0, 9 ): SCREAMING_SNAKE_CASE_ = -i assert all(linked_list[i] == -i for i in range(0, 9 ) ) is True linked_list.reverse() assert str(__a ) == "->".join(str(__a ) for i in range(-8, 1 ) ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = [ -9, 100, Node(77_345_112 ), '''dlrow olleH''', 7, 5_555, 0, -1_9_2.5_5_5_5_5, '''Hello, world!''', 7_7.9, Node(10 ), None, None, 1_2.2_0, ] SCREAMING_SNAKE_CASE_ = LinkedList() for i in test_input: linked_list.insert_tail(__a ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(__a ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head SCREAMING_SNAKE_CASE_ = linked_list.delete_head() assert result == -9 assert ( str(__a ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail SCREAMING_SNAKE_CASE_ = linked_list.delete_tail() assert result == 1_2.2 assert ( str(__a ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list SCREAMING_SNAKE_CASE_ = linked_list.delete_nth(10 ) assert result is None assert ( str(__a ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('''Hello again, world!''' ) ) assert ( str(__a ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(__a ) assert ( str(__a ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(__a ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def _lowerCamelCase ( ): from doctest import testmod testmod() SCREAMING_SNAKE_CASE_ = LinkedList() linked_list.insert_head(input('''Inserting 1st at head ''' ).strip() ) linked_list.insert_head(input('''Inserting 2nd at head ''' ).strip() ) print('''\nPrint list:''' ) linked_list.print_list() linked_list.insert_tail(input('''\nInserting 1st at tail ''' ).strip() ) linked_list.insert_tail(input('''Inserting 2nd at tail ''' ).strip() ) print('''\nPrint list:''' ) linked_list.print_list() print('''\nDelete head''' ) linked_list.delete_head() print('''Delete tail''' ) linked_list.delete_tail() print('''\nPrint list:''' ) linked_list.print_list() print('''\nReverse linked list''' ) linked_list.reverse() print('''\nPrint list:''' ) linked_list.print_list() print('''\nString representation of linked list:''' ) print(__a ) print('''\nReading/changing Node data using indexing:''' ) print(F'Element at Position 1: {linked_list[1]}' ) SCREAMING_SNAKE_CASE_ = input('''Enter New Value: ''' ).strip() print('''New list:''' ) print(__a ) print(F'length of linked_list is : {len(__a )}' ) if __name__ == "__main__": main()
628
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class snake_case ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.text_to_image( prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = pipe.image_variation(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
628
1
"""simple docstring""" from __future__ import annotations import queue class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = data SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None def _lowerCamelCase ( ): print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE_ = input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE_ = queue.Queue() SCREAMING_SNAKE_CASE_ = TreeNode(int(__a ) ) q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ = q.get() SCREAMING_SNAKE_CASE_ = F'Enter the left node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ = left_node q.put(__a ) SCREAMING_SNAKE_CASE_ = F'Enter the right node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ = right_node q.put(__a ) raise def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return print(node.data, end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return in_order(node.left ) print(node.data, end=''',''' ) in_order(node.right ) def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data, end=''',''' ) def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return SCREAMING_SNAKE_CASE_ = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ = q.get() print(node_dequeued.data, end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return SCREAMING_SNAKE_CASE_ = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ = [] while not q.empty(): SCREAMING_SNAKE_CASE_ = q.get() print(node_dequeued.data, end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__a ) def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = node while n or stack: while n: # start from root node, find its left child print(n.data, end=''',''' ) stack.append(__a ) SCREAMING_SNAKE_CASE_ = n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE_ = stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE_ = n.right def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = node while n or stack: while n: stack.append(__a ) SCREAMING_SNAKE_CASE_ = n.left SCREAMING_SNAKE_CASE_ = stack.pop() print(n.data, end=''',''' ) SCREAMING_SNAKE_CASE_ = n.right def _lowerCamelCase ( __a ): if not isinstance(__a, __a ) or not node: return SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = [], [] SCREAMING_SNAKE_CASE_ = node stacka.append(__a ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE_ = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__a ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data, end=''',''' ) def _lowerCamelCase ( __a = "", __a=50, __a="*" ): if not s: return "\n" + width * char SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = divmod(width - len(__a ) - 2, 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt('Binary Tree Traversals')) lowerCAmelCase__ = build_tree() print(prompt('Pre Order Traversal')) pre_order(node) print(prompt() + '\n') print(prompt('In Order Traversal')) in_order(node) print(prompt() + '\n') print(prompt('Post Order Traversal')) post_order(node) print(prompt() + '\n') print(prompt('Level Order Traversal')) level_order(node) print(prompt() + '\n') print(prompt('Actual Level Order Traversal')) level_order_actual(node) print('*' * 50 + '\n') print(prompt('Pre Order Traversal - Iteration Version')) pre_order_iter(node) print(prompt() + '\n') print(prompt('In Order Traversal - Iteration Version')) in_order_iter(node) print(prompt() + '\n') print(prompt('Post Order Traversal - Iteration Version')) post_order_iter(node) print(prompt())
628
"""simple docstring""" import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def _lowerCamelCase ( __a ): # picklable for multiprocessing return x.sum() def _lowerCamelCase ( __a ): # picklable for multiprocessing return i + 1 @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = [1, 2] SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': [1, 2], '''b''': [3, 4]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 1}, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = [2, 3] SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': [2, 3], '''b''': [4, 5]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 2}, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = 2 self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = {'''a''': np.eye(2 ), '''b''': np.zeros(3 ), '''c''': np.ones(2 )} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 0, '''c''': 2} SCREAMING_SNAKE_CASE_ = { '''a''': np.eye(2 ).astype(SCREAMING_SNAKE_CASE_ ), '''b''': np.zeros(3 ).astype(SCREAMING_SNAKE_CASE_ ), '''c''': np.ones(2 ).astype(SCREAMING_SNAKE_CASE_ ), } self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): # can't pickle a local lambda map_nested(lambda SCREAMING_SNAKE_CASE_ : x + 1 , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 3, '''b''': 4} SCREAMING_SNAKE_CASE_ = {'''a''': 5, '''b''': 6} SCREAMING_SNAKE_CASE_ = sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" class snake_case : UpperCAmelCase__ = '''bar''' SCREAMING_SNAKE_CASE_ = Foo() self.assertEqual(foo.my_attr , '''bar''' ) with temporary_assignment(SCREAMING_SNAKE_CASE_ , '''my_attr''' , '''BAR''' ): self.assertEqual(foo.my_attr , '''BAR''' ) self.assertEqual(foo.my_attr , '''bar''' ) @pytest.mark.parametrize( '''iterable_length, num_proc, expected_num_proc''', [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ], ) def _lowerCamelCase ( __a, __a, __a ): with patch('''datasets.utils.py_utils._single_map_nested''' ) as mock_single_map_nested, patch( '''datasets.parallel.parallel.Pool''' ) as mock_multiprocessing_pool: SCREAMING_SNAKE_CASE_ = {F'{i}': i for i in range(__a )} SCREAMING_SNAKE_CASE_ = map_nested(lambda __a : x + 10, __a, num_proc=__a, parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class snake_case ( __lowercase ): @require_tf def _lowercase (self ): """simple docstring""" import tensorflow as tf from tensorflow.keras import layers SCREAMING_SNAKE_CASE_ = layers.Dense(2 ) def gen_random_output(): SCREAMING_SNAKE_CASE_ = tf.random.uniform((1, 3) ) return model(SCREAMING_SNAKE_CASE_ ).numpy() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def _lowercase (self ): """simple docstring""" import torch def gen_random_output(): SCREAMING_SNAKE_CASE_ = torch.nn.Linear(3 , 2 ) SCREAMING_SNAKE_CASE_ = torch.rand(1 , 3 ) return model(SCREAMING_SNAKE_CASE_ ).detach().numpy() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def _lowercase (self ): """simple docstring""" def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize('''input_data''', [{}] ) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).data assert output_data == input_data @pytest.mark.parametrize( '''data, expected_output''', [ ({}, []), ([], []), ('''foo''', ['''foo''']), (['''foo''', '''bar'''], ['''foo''', '''bar''']), ([['''foo''', '''bar''']], ['''foo''', '''bar''']), ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']), ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']), ({'''a''': 1, '''b''': 2}, [1, 2]), ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]), ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]), ], ) def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).flatten() assert output == expected_output def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = A(x=1, y='''foobar''' ) SCREAMING_SNAKE_CASE_ = {'''x''': 1, '''y''': '''foobar'''} assert asdict(__a ) == expected_output SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': A(x=10, y='''foo''' )}, '''c''': [A(x=20, y='''bar''' )]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]} assert asdict(__a ) == expected_output with pytest.raises(__a ): asdict([1, A(x=10, y='''foo''' )] ) def _lowerCamelCase ( __a ): return text.split() def _lowerCamelCase ( __a ): yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def _lowerCamelCase ( ): with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = [] for yield_time, content in iflatmap_unordered( __a, _aseconds_generator_of_aitems_with_timing, kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__a ) assert out.count('''a''' ) == 2 assert out.count('''b''' ) == 2 assert len(__a ) == 4
628
1
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _lowerCamelCase ( __a, __a=0.9_9_9, __a="cosine", ): if alpha_transform_type == "cosine": def alpha_bar_fn(__a ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__a ): return math.exp(t * -1_2.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) SCREAMING_SNAKE_CASE_ = [] for i in range(__a ): SCREAMING_SNAKE_CASE_ = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__a ) / alpha_bar_fn(__a ), __a ) ) return torch.tensor(__a, dtype=torch.floataa ) class snake_case ( __lowercase , __lowercase ): UpperCAmelCase__ = [e.name for e in KarrasDiffusionSchedulers] UpperCAmelCase__ = 2 @register_to_config def __init__(self , SCREAMING_SNAKE_CASE_ = 10_00 , SCREAMING_SNAKE_CASE_ = 0.0_00_85 , SCREAMING_SNAKE_CASE_ = 0.0_12 , SCREAMING_SNAKE_CASE_ = "linear" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "epsilon" , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = "linspace" , SCREAMING_SNAKE_CASE_ = 0 , ): """simple docstring""" if trained_betas is not None: SCREAMING_SNAKE_CASE_ = torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE_ = torch.linspace(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) SCREAMING_SNAKE_CASE_ = 1.0 - self.betas SCREAMING_SNAKE_CASE_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = use_karras_sigmas def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" if schedule_timesteps is None: SCREAMING_SNAKE_CASE_ = self.timesteps SCREAMING_SNAKE_CASE_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: SCREAMING_SNAKE_CASE_ = 1 if len(SCREAMING_SNAKE_CASE_ ) > 1 else 0 else: SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep SCREAMING_SNAKE_CASE_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self ): """simple docstring""" if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = num_inference_steps SCREAMING_SNAKE_CASE_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": SCREAMING_SNAKE_CASE_ = np.linspace(0 , num_train_timesteps - 1 , SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )[::-1].copy() elif self.config.timestep_spacing == "leading": SCREAMING_SNAKE_CASE_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(0 , SCREAMING_SNAKE_CASE_ ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": SCREAMING_SNAKE_CASE_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(SCREAMING_SNAKE_CASE_ , 0 , -step_ratio )).round().copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps -= 1 else: raise ValueError( f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) SCREAMING_SNAKE_CASE_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.interp(SCREAMING_SNAKE_CASE_ , np.arange(0 , len(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) if self.config.use_karras_sigmas: SCREAMING_SNAKE_CASE_ = self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE_ , num_inference_steps=self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for sigma in sigmas] ) SCREAMING_SNAKE_CASE_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = timesteps.to(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = timesteps.to(device=SCREAMING_SNAKE_CASE_ ) # empty dt and derivative SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter SCREAMING_SNAKE_CASE_ = defaultdict(SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) # get distribution SCREAMING_SNAKE_CASE_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range SCREAMING_SNAKE_CASE_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) SCREAMING_SNAKE_CASE_ = low_idx + 1 SCREAMING_SNAKE_CASE_ = log_sigmas[low_idx] SCREAMING_SNAKE_CASE_ = log_sigmas[high_idx] # interpolate sigmas SCREAMING_SNAKE_CASE_ = (low - log_sigma) / (low - high) SCREAMING_SNAKE_CASE_ = np.clip(SCREAMING_SNAKE_CASE_ , 0 , 1 ) # transform interpolation to time range SCREAMING_SNAKE_CASE_ = (1 - w) * low_idx + w * high_idx SCREAMING_SNAKE_CASE_ = t.reshape(sigma.shape ) return t def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = in_sigmas[-1].item() SCREAMING_SNAKE_CASE_ = in_sigmas[0].item() SCREAMING_SNAKE_CASE_ = 7.0 # 7.0 is the value used in the paper SCREAMING_SNAKE_CASE_ = np.linspace(0 , 1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = sigma_min ** (1 / rho) SCREAMING_SNAKE_CASE_ = sigma_max ** (1 / rho) SCREAMING_SNAKE_CASE_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self ): """simple docstring""" return self.dt is None def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) # advance index counter by 1 SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = self.sigmas[step_index - 1] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE_ = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: SCREAMING_SNAKE_CASE_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep SCREAMING_SNAKE_CASE_ = sigma_next - sigma_hat # store for 2nd order step SCREAMING_SNAKE_CASE_ = derivative SCREAMING_SNAKE_CASE_ = dt SCREAMING_SNAKE_CASE_ = sample else: # 2. 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_next SCREAMING_SNAKE_CASE_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample SCREAMING_SNAKE_CASE_ = self.dt SCREAMING_SNAKE_CASE_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE_ ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = [self.index_for_timestep(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for t in timesteps] SCREAMING_SNAKE_CASE_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): SCREAMING_SNAKE_CASE_ = sigma.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_ = original_samples + noise * sigma return noisy_samples def __len__(self ): """simple docstring""" return self.config.num_train_timesteps
628
"""simple docstring""" import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCAmelCase__ = { 'facebook/maskformer-swin-base-ade': ( 'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowerCAmelCase__ = logging.get_logger(__name__) class snake_case ( __lowercase ): UpperCAmelCase__ = '''maskformer''' UpperCAmelCase__ = {'''hidden_size''': '''mask_feature_size'''} UpperCAmelCase__ = ['''resnet''', '''swin'''] UpperCAmelCase__ = ['''detr'''] def __init__(self , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 20.0 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k SCREAMING_SNAKE_CASE_ = SwinConfig( image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = backbone_config.pop('''model_type''' ) SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ' f'Supported model types: {",".join(self.backbones_supported )}' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 SCREAMING_SNAKE_CASE_ = DetrConfig() else: # verify that the decoder is supported SCREAMING_SNAKE_CASE_ = ( decoder_config.pop('''model_type''' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'Transformer Decoder {decoder_type} not supported, please use one of' f' {",".join(self.decoders_supported )}' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[decoder_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = backbone_config SCREAMING_SNAKE_CASE_ = decoder_config # main feature dimension for the model SCREAMING_SNAKE_CASE_ = fpn_feature_size SCREAMING_SNAKE_CASE_ = mask_feature_size # initializer SCREAMING_SNAKE_CASE_ = init_std SCREAMING_SNAKE_CASE_ = init_xavier_std # Hungarian matcher && loss SCREAMING_SNAKE_CASE_ = cross_entropy_weight SCREAMING_SNAKE_CASE_ = dice_weight SCREAMING_SNAKE_CASE_ = mask_weight SCREAMING_SNAKE_CASE_ = use_auxiliary_loss SCREAMING_SNAKE_CASE_ = no_object_weight SCREAMING_SNAKE_CASE_ = output_auxiliary_logits SCREAMING_SNAKE_CASE_ = self.decoder_config.encoder_attention_heads SCREAMING_SNAKE_CASE_ = self.decoder_config.num_hidden_layers super().__init__(**SCREAMING_SNAKE_CASE_ ) @classmethod def _lowercase (cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return cls( backbone_config=SCREAMING_SNAKE_CASE_ , decoder_config=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ = self.decoder_config.to_dict() SCREAMING_SNAKE_CASE_ = self.__class__.model_type return output
628
1
"""simple docstring""" # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import sys import transformers lowerCAmelCase__ = '3' print('Python version:', sys.version) print('transformers version:', transformers.__version__) try: import torch print('Torch version:', torch.__version__) print('Cuda available:', torch.cuda.is_available()) print('Cuda version:', torch.version.cuda) print('CuDNN version:', torch.backends.cudnn.version()) print('Number of GPUs available:', torch.cuda.device_count()) print('NCCL version:', torch.cuda.nccl.version()) except ImportError: print('Torch version:', None) try: import deepspeed print('DeepSpeed version:', deepspeed.__version__) except ImportError: print('DeepSpeed version:', None) try: import tensorflow as tf print('TensorFlow version:', tf.__version__) print('TF GPUs available:', bool(tf.config.list_physical_devices('GPU'))) print('Number of TF GPUs available:', len(tf.config.list_physical_devices('GPU'))) except ImportError: print('TensorFlow version:', None)
628
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] SCREAMING_SNAKE_CASE_ = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE_ = [4, 4, 4, 4] SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE_ = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE_ = 128 elif "large" in model_name: SCREAMING_SNAKE_CASE_ = 192 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE_ = 256 elif "huge" in model_name: SCREAMING_SNAKE_CASE_ = 352 # set label information SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE_ = '''imagenet-22k-id2label.json''' else: SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(__a, __a, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = FocalNetConfig( embed_dim=__a, depths=__a, focal_levels=__a, focal_windows=__a, use_conv_embed=__a, idalabel=__a, labelaid=__a, use_post_layernorm=__a, use_layerscale=__a, ) return config def _lowerCamelCase ( __a ): 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 "layers" in name: SCREAMING_SNAKE_CASE_ = '''encoder.''' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE_ = name.replace('''encoder.layers''', '''encoder.stages''' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('''downsample.proj''', '''downsample.projection''' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ = name.replace('''blocks''', '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.f''', '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.h''', '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.proj''', '''modulation.projection_out''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE_ = '''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE_ = '''layernorm.bias''' if "head" in name: SCREAMING_SNAKE_CASE_ = name.replace('''head''', '''classifier''' ) else: SCREAMING_SNAKE_CASE_ = '''focalnet.''' + name return name def _lowerCamelCase ( __a, __a, __a=False ): # fmt: off SCREAMING_SNAKE_CASE_ = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on SCREAMING_SNAKE_CASE_ = model_name_to_url[model_name] print('''Checkpoint URL: ''', __a ) SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(__a, map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = get_focalnet_config(__a ) SCREAMING_SNAKE_CASE_ = FocalNetForImageClassification(__a ) model.eval() # load state dict model.load_state_dict(__a ) # verify conversion SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = BitImageProcessor( do_resize=__a, size={'''shortest_edge''': 256}, resample=PILImageResampling.BILINEAR, do_center_crop=__a, crop_size=224, do_normalize=__a, image_mean=__a, image_std=__a, ) SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__a, stream=__a ).raw ) SCREAMING_SNAKE_CASE_ = processor(images=__a, return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE_ = image_transforms(__a ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values, __a, atol=1E-4 ) SCREAMING_SNAKE_CASE_ = model(**__a ) SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(-1 ).item() print('''Predicted class:''', model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''', outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE_ = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE_ = torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8] ) assert torch.allclose(outputs.logits[0, :3], __a, atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model and processor of {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if push_to_hub: print(F'Pushing model and processor of {model_name} to the hub...' ) model.push_to_hub(F'{model_name}' ) processor.push_to_hub(F'{model_name}' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
628
1
"""simple docstring""" 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)
628
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class snake_case ( __lowercase ): UpperCAmelCase__ = '''glpn''' def __init__(self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[8, 4, 2, 1] , SCREAMING_SNAKE_CASE_=[32, 64, 1_60, 2_56] , SCREAMING_SNAKE_CASE_=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE_=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[1, 2, 5, 8] , SCREAMING_SNAKE_CASE_=[4, 4, 4, 4] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1e-6 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=-1 , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) 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_ = initializer_range SCREAMING_SNAKE_CASE_ = drop_path_rate SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = decoder_hidden_size SCREAMING_SNAKE_CASE_ = max_depth SCREAMING_SNAKE_CASE_ = head_in_index
628
1
"""simple docstring""" import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger('transformers.models.encodec') lowerCAmelCase__ = { 'quantizer.vq.layers.*._codebook.inited': 'quantizer.layers.*.codebook.inited', 'quantizer.vq.layers.*._codebook.cluster_size': 'quantizer.layers.*.codebook.cluster_size', 'quantizer.vq.layers.*._codebook.embed': 'quantizer.layers.*.codebook.embed', 'quantizer.vq.layers.*._codebook.embed_avg': 'quantizer.layers.*.codebook.embed_avg', } lowerCAmelCase__ = { 'encoder.model.0.conv.conv': 'encoder.layers.0.conv', 'encoder.model.1.block.1.conv.conv': 'encoder.layers.1.block.1.conv', 'encoder.model.1.block.3.conv.conv': 'encoder.layers.1.block.3.conv', 'encoder.model.1.shortcut.conv.conv': 'encoder.layers.1.shortcut.conv', 'encoder.model.3.conv.conv': 'encoder.layers.3.conv', 'encoder.model.4.block.1.conv.conv': 'encoder.layers.4.block.1.conv', 'encoder.model.4.block.3.conv.conv': 'encoder.layers.4.block.3.conv', 'encoder.model.4.shortcut.conv.conv': 'encoder.layers.4.shortcut.conv', 'encoder.model.6.conv.conv': 'encoder.layers.6.conv', 'encoder.model.7.block.1.conv.conv': 'encoder.layers.7.block.1.conv', 'encoder.model.7.block.3.conv.conv': 'encoder.layers.7.block.3.conv', 'encoder.model.7.shortcut.conv.conv': 'encoder.layers.7.shortcut.conv', 'encoder.model.9.conv.conv': 'encoder.layers.9.conv', 'encoder.model.10.block.1.conv.conv': 'encoder.layers.10.block.1.conv', 'encoder.model.10.block.3.conv.conv': 'encoder.layers.10.block.3.conv', 'encoder.model.10.shortcut.conv.conv': 'encoder.layers.10.shortcut.conv', 'encoder.model.12.conv.conv': 'encoder.layers.12.conv', 'encoder.model.13.lstm': 'encoder.layers.13.lstm', 'encoder.model.15.conv.conv': 'encoder.layers.15.conv', } lowerCAmelCase__ = { 'encoder.model.0.conv.norm': 'encoder.layers.0.norm', 'encoder.model.1.block.1.conv.norm': 'encoder.layers.1.block.1.norm', 'encoder.model.1.block.3.conv.norm': 'encoder.layers.1.block.3.norm', 'encoder.model.1.shortcut.conv.norm': 'encoder.layers.1.shortcut.norm', 'encoder.model.3.conv.norm': 'encoder.layers.3.norm', 'encoder.model.4.block.1.conv.norm': 'encoder.layers.4.block.1.norm', 'encoder.model.4.block.3.conv.norm': 'encoder.layers.4.block.3.norm', 'encoder.model.4.shortcut.conv.norm': 'encoder.layers.4.shortcut.norm', 'encoder.model.6.conv.norm': 'encoder.layers.6.norm', 'encoder.model.7.block.1.conv.norm': 'encoder.layers.7.block.1.norm', 'encoder.model.7.block.3.conv.norm': 'encoder.layers.7.block.3.norm', 'encoder.model.7.shortcut.conv.norm': 'encoder.layers.7.shortcut.norm', 'encoder.model.9.conv.norm': 'encoder.layers.9.norm', 'encoder.model.10.block.1.conv.norm': 'encoder.layers.10.block.1.norm', 'encoder.model.10.block.3.conv.norm': 'encoder.layers.10.block.3.norm', 'encoder.model.10.shortcut.conv.norm': 'encoder.layers.10.shortcut.norm', 'encoder.model.12.conv.norm': 'encoder.layers.12.norm', 'encoder.model.15.conv.norm': 'encoder.layers.15.norm', } lowerCAmelCase__ = { 'decoder.model.0.conv.conv': 'decoder.layers.0.conv', 'decoder.model.1.lstm': 'decoder.layers.1.lstm', 'decoder.model.3.convtr.convtr': 'decoder.layers.3.conv', 'decoder.model.4.block.1.conv.conv': 'decoder.layers.4.block.1.conv', 'decoder.model.4.block.3.conv.conv': 'decoder.layers.4.block.3.conv', 'decoder.model.4.shortcut.conv.conv': 'decoder.layers.4.shortcut.conv', 'decoder.model.6.convtr.convtr': 'decoder.layers.6.conv', 'decoder.model.7.block.1.conv.conv': 'decoder.layers.7.block.1.conv', 'decoder.model.7.block.3.conv.conv': 'decoder.layers.7.block.3.conv', 'decoder.model.7.shortcut.conv.conv': 'decoder.layers.7.shortcut.conv', 'decoder.model.9.convtr.convtr': 'decoder.layers.9.conv', 'decoder.model.10.block.1.conv.conv': 'decoder.layers.10.block.1.conv', 'decoder.model.10.block.3.conv.conv': 'decoder.layers.10.block.3.conv', 'decoder.model.10.shortcut.conv.conv': 'decoder.layers.10.shortcut.conv', 'decoder.model.12.convtr.convtr': 'decoder.layers.12.conv', 'decoder.model.13.block.1.conv.conv': 'decoder.layers.13.block.1.conv', 'decoder.model.13.block.3.conv.conv': 'decoder.layers.13.block.3.conv', 'decoder.model.13.shortcut.conv.conv': 'decoder.layers.13.shortcut.conv', 'decoder.model.15.conv.conv': 'decoder.layers.15.conv', } lowerCAmelCase__ = { 'decoder.model.0.conv.norm': 'decoder.layers.0.norm', 'decoder.model.3.convtr.norm': 'decoder.layers.3.norm', 'decoder.model.4.block.1.conv.norm': 'decoder.layers.4.block.1.norm', 'decoder.model.4.block.3.conv.norm': 'decoder.layers.4.block.3.norm', 'decoder.model.4.shortcut.conv.norm': 'decoder.layers.4.shortcut.norm', 'decoder.model.6.convtr.norm': 'decoder.layers.6.norm', 'decoder.model.7.block.1.conv.norm': 'decoder.layers.7.block.1.norm', 'decoder.model.7.block.3.conv.norm': 'decoder.layers.7.block.3.norm', 'decoder.model.7.shortcut.conv.norm': 'decoder.layers.7.shortcut.norm', 'decoder.model.9.convtr.norm': 'decoder.layers.9.norm', 'decoder.model.10.block.1.conv.norm': 'decoder.layers.10.block.1.norm', 'decoder.model.10.block.3.conv.norm': 'decoder.layers.10.block.3.norm', 'decoder.model.10.shortcut.conv.norm': 'decoder.layers.10.shortcut.norm', 'decoder.model.12.convtr.norm': 'decoder.layers.12.norm', 'decoder.model.13.block.1.conv.norm': 'decoder.layers.13.block.1.norm', 'decoder.model.13.block.3.conv.norm': 'decoder.layers.13.block.3.norm', 'decoder.model.13.shortcut.conv.norm': 'decoder.layers.13.shortcut.norm', 'decoder.model.15.conv.norm': 'decoder.layers.15.norm', } lowerCAmelCase__ = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } lowerCAmelCase__ = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } lowerCAmelCase__ = [] lowerCAmelCase__ = [] def _lowerCamelCase ( __a, __a, __a, __a, __a ): for attribute in key.split('''.''' ): SCREAMING_SNAKE_CASE_ = getattr(__a, __a ) if weight_type is not None: SCREAMING_SNAKE_CASE_ = getattr(__a, __a ).shape else: SCREAMING_SNAKE_CASE_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE_ = value elif weight_type == "bias": SCREAMING_SNAKE_CASE_ = value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE_ = value elif weight_type == "running_var": SCREAMING_SNAKE_CASE_ = value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_ih_l0": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_hh_l0": SCREAMING_SNAKE_CASE_ = value elif weight_type == "bias_ih_l0": SCREAMING_SNAKE_CASE_ = value elif weight_type == "bias_hh_l0": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_ih_l1": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_hh_l1": SCREAMING_SNAKE_CASE_ = value elif weight_type == "bias_ih_l1": SCREAMING_SNAKE_CASE_ = value elif weight_type == "bias_hh_l1": SCREAMING_SNAKE_CASE_ = value else: SCREAMING_SNAKE_CASE_ = value logger.info(F'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' ) def _lowerCamelCase ( __a, __a ): for key in ignore_keys: if key.endswith('''.*''' ): if name.startswith(key[:-1] ): return True elif ".*." in key: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = key.split('''.*.''' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = [] if model_name == "encodec_24khz" or "encodec_32khz": SCREAMING_SNAKE_CASE_ = MAPPING_24K elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE_ = MAPPING_48K else: raise ValueError(F'Unsupported model: {model_name}' ) for name, value in orig_dict.items(): if should_ignore(__a, __a ): logger.info(F'{name} was ignored' ) continue SCREAMING_SNAKE_CASE_ = False for key, mapped_key in MAPPING.items(): if "*" in key: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = key.split('''.*.''' ) if prefix in name and suffix in name: SCREAMING_SNAKE_CASE_ = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('''embed''' ) and name.endswith('''embed_avg''' ): continue SCREAMING_SNAKE_CASE_ = True if "*" in mapped_key: SCREAMING_SNAKE_CASE_ = name.split(__a )[0].split('''.''' )[-2] SCREAMING_SNAKE_CASE_ = mapped_key.replace('''*''', __a ) if "weight_g" in name: SCREAMING_SNAKE_CASE_ = '''weight_g''' elif "weight_v" in name: SCREAMING_SNAKE_CASE_ = '''weight_v''' elif "weight_ih_l0" in name: SCREAMING_SNAKE_CASE_ = '''weight_ih_l0''' elif "weight_hh_l0" in name: SCREAMING_SNAKE_CASE_ = '''weight_hh_l0''' elif "bias_ih_l0" in name: SCREAMING_SNAKE_CASE_ = '''bias_ih_l0''' elif "bias_hh_l0" in name: SCREAMING_SNAKE_CASE_ = '''bias_hh_l0''' elif "weight_ih_l1" in name: SCREAMING_SNAKE_CASE_ = '''weight_ih_l1''' elif "weight_hh_l1" in name: SCREAMING_SNAKE_CASE_ = '''weight_hh_l1''' elif "bias_ih_l1" in name: SCREAMING_SNAKE_CASE_ = '''bias_ih_l1''' elif "bias_hh_l1" in name: SCREAMING_SNAKE_CASE_ = '''bias_hh_l1''' elif "bias" in name: SCREAMING_SNAKE_CASE_ = '''bias''' elif "weight" in name: SCREAMING_SNAKE_CASE_ = '''weight''' elif "running_mean" in name: SCREAMING_SNAKE_CASE_ = '''running_mean''' elif "running_var" in name: SCREAMING_SNAKE_CASE_ = '''running_var''' elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE_ = '''num_batches_tracked''' else: SCREAMING_SNAKE_CASE_ = None set_recursively(__a, __a, __a, __a, __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(F'Unused weights: {unused_weights}' ) @torch.no_grad() def _lowerCamelCase ( __a, __a, __a, __a=None, __a=None, ): if config_path is not None: SCREAMING_SNAKE_CASE_ = EncodecConfig.from_pretrained(__a ) else: SCREAMING_SNAKE_CASE_ = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": SCREAMING_SNAKE_CASE_ = [8, 5, 4, 4] SCREAMING_SNAKE_CASE_ = [2.2] SCREAMING_SNAKE_CASE_ = 64 SCREAMING_SNAKE_CASE_ = 32_000 SCREAMING_SNAKE_CASE_ = 2_048 SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = False elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE_ = [8, 5, 4, 2] SCREAMING_SNAKE_CASE_ = [3.0, 6.0, 1_2.0, 2_4.0] SCREAMING_SNAKE_CASE_ = 48_000 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = '''time_group_norm''' SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = 1.0 SCREAMING_SNAKE_CASE_ = 0.0_1 else: raise ValueError(F'Unknown model name: {model_name}' ) SCREAMING_SNAKE_CASE_ = EncodecModel(__a ) SCREAMING_SNAKE_CASE_ = EncodecFeatureExtractor( feature_size=config.audio_channels, sampling_rate=config.sampling_rate, chunk_length_s=config.chunk_length_s, overlap=config.overlap, ) feature_extractor.save_pretrained(__a ) SCREAMING_SNAKE_CASE_ = torch.load(__a ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights SCREAMING_SNAKE_CASE_ = original_checkpoint['''best_state'''] recursively_load_weights(__a, __a, __a ) model.save_pretrained(__a ) if repo_id: print('''Pushing to the hub...''' ) feature_extractor.push_to_hub(__a ) model.push_to_hub(__a ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '--model', default='encodec_24khz', type=str, help='The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.', ) parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) lowerCAmelCase__ = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
628
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = KandinskyVaaControlnetPipeline UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCAmelCase__ = False @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return self.time_input_dim @property def _lowercase (self ): """simple docstring""" return self.time_input_dim * 4 @property def _lowercase (self ): """simple docstring""" return 1_00 @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE_ = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def _lowercase (self ): """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = VQModel(**self.dummy_movq_kwargs ) return model def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.dummy_unet SCREAMING_SNAKE_CASE_ = self.dummy_movq SCREAMING_SNAKE_CASE_ = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='''linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , steps_offset=1 , prediction_type='''epsilon''' , thresholding=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): """simple docstring""" SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( SCREAMING_SNAKE_CASE_ ) # create hint SCREAMING_SNAKE_CASE_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = { '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 64, '''width''': 64, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''cpu''' SCREAMING_SNAKE_CASE_ = self.get_dummy_components() SCREAMING_SNAKE_CASE_ = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = output.images SCREAMING_SNAKE_CASE_ = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[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.6_95_98_26, 0.86_82_79, 0.7_55_80_92, 0.68_76_94_67, 0.85_80_58_04, 0.65_97_74_96, 0.44_88_53_02, 0.5_95_91_11, 0.4_25_15_95] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy''' ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE_ ) ).float() / 2_55.0 SCREAMING_SNAKE_CASE_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) SCREAMING_SNAKE_CASE_ = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = KandinskyVaaControlnetPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''A robot, 4k photo''' SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = pipe_prior( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipeline( image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , hint=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=1_00 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
628
1
"""simple docstring""" import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = np.argmax(__a, axis=1 ) return np.sum(outputs == labels ) def _lowerCamelCase ( __a ): with open(__a, encoding='''utf_8''' ) as f: SCREAMING_SNAKE_CASE_ = csv.reader(__a ) SCREAMING_SNAKE_CASE_ = [] next(__a ) # skip the first line for line in tqdm(__a ): output.append((''' '''.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _lowerCamelCase ( __a, __a, __a, __a, __a, __a ): SCREAMING_SNAKE_CASE_ = [] for dataset in encoded_datasets: SCREAMING_SNAKE_CASE_ = len(__a ) SCREAMING_SNAKE_CASE_ = np.zeros((n_batch, 2, input_len), dtype=np.intaa ) SCREAMING_SNAKE_CASE_ = np.zeros((n_batch, 2), dtype=np.intaa ) SCREAMING_SNAKE_CASE_ = np.full((n_batch, 2, input_len), fill_value=-100, dtype=np.intaa ) SCREAMING_SNAKE_CASE_ = np.zeros((n_batch,), dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(__a ): SCREAMING_SNAKE_CASE_ = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] SCREAMING_SNAKE_CASE_ = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] SCREAMING_SNAKE_CASE_ = with_conta SCREAMING_SNAKE_CASE_ = with_conta SCREAMING_SNAKE_CASE_ = len(__a ) - 1 SCREAMING_SNAKE_CASE_ = len(__a ) - 1 SCREAMING_SNAKE_CASE_ = with_conta SCREAMING_SNAKE_CASE_ = with_conta SCREAMING_SNAKE_CASE_ = mc_label SCREAMING_SNAKE_CASE_ = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(__a ) for t in all_inputs ) ) return tensor_datasets def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() parser.add_argument('''--model_name''', type=__a, default='''openai-gpt''', help='''pretrained model name''' ) parser.add_argument('''--do_train''', action='''store_true''', help='''Whether to run training.''' ) parser.add_argument('''--do_eval''', action='''store_true''', help='''Whether to run eval on the dev set.''' ) parser.add_argument( '''--output_dir''', default=__a, type=__a, required=__a, help='''The output directory where the model predictions and checkpoints will be written.''', ) parser.add_argument('''--train_dataset''', type=__a, default='''''' ) parser.add_argument('''--eval_dataset''', type=__a, default='''''' ) parser.add_argument('''--seed''', type=__a, default=42 ) parser.add_argument('''--num_train_epochs''', type=__a, default=3 ) parser.add_argument('''--train_batch_size''', type=__a, default=8 ) parser.add_argument('''--eval_batch_size''', type=__a, default=16 ) parser.add_argument('''--adam_epsilon''', default=1E-8, type=__a, help='''Epsilon for Adam optimizer.''' ) parser.add_argument('''--max_grad_norm''', type=__a, default=1 ) parser.add_argument( '''--max_steps''', default=-1, type=__a, help=( '''If > 0: set total number of training steps to perform. Override num_train_epochs.''' ), ) parser.add_argument( '''--gradient_accumulation_steps''', type=__a, default=1, help='''Number of updates steps to accumulate before performing a backward/update pass.''', ) parser.add_argument('''--learning_rate''', type=__a, default=6.25E-5 ) parser.add_argument('''--warmup_steps''', default=0, type=__a, help='''Linear warmup over warmup_steps.''' ) parser.add_argument('''--lr_schedule''', type=__a, default='''warmup_linear''' ) parser.add_argument('''--weight_decay''', type=__a, default=0.0_1 ) parser.add_argument('''--lm_coef''', type=__a, default=0.9 ) parser.add_argument('''--n_valid''', type=__a, default=374 ) parser.add_argument('''--server_ip''', type=__a, default='''''', help='''Can be used for distant debugging.''' ) parser.add_argument('''--server_port''', type=__a, default='''''', help='''Can be used for distant debugging.''' ) SCREAMING_SNAKE_CASE_ = parser.parse_args() print(__a ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('''Waiting for debugger attach''' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=__a ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) SCREAMING_SNAKE_CASE_ = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) SCREAMING_SNAKE_CASE_ = torch.cuda.device_count() logger.info('''device: {}, n_gpu {}'''.format(__a, __a ) ) if not args.do_train and not args.do_eval: raise ValueError('''At least one of `do_train` or `do_eval` must be True.''' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset SCREAMING_SNAKE_CASE_ = ['''_start_''', '''_delimiter_''', '''_classify_'''] SCREAMING_SNAKE_CASE_ = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(__a ) SCREAMING_SNAKE_CASE_ = tokenizer.convert_tokens_to_ids(__a ) SCREAMING_SNAKE_CASE_ = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(__a ) ) model.to(__a ) # Load and encode the datasets def tokenize_and_encode(__a ): if isinstance(__a, __a ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(__a ) ) elif isinstance(__a, __a ): return obj return [tokenize_and_encode(__a ) for o in obj] logger.info('''Encoding dataset...''' ) SCREAMING_SNAKE_CASE_ = load_rocstories_dataset(args.train_dataset ) SCREAMING_SNAKE_CASE_ = load_rocstories_dataset(args.eval_dataset ) SCREAMING_SNAKE_CASE_ = (train_dataset, eval_dataset) SCREAMING_SNAKE_CASE_ = tokenize_and_encode(__a ) # Compute the max input length for the Transformer SCREAMING_SNAKE_CASE_ = model.config.n_positions // 2 - 2 SCREAMING_SNAKE_CASE_ = max( len(story[:max_length] ) + max(len(conta[:max_length] ), len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) SCREAMING_SNAKE_CASE_ = min(__a, model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders SCREAMING_SNAKE_CASE_ = pre_process_datasets(__a, __a, __a, *__a ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = tensor_datasets[0], tensor_datasets[1] SCREAMING_SNAKE_CASE_ = TensorDataset(*__a ) SCREAMING_SNAKE_CASE_ = RandomSampler(__a ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, sampler=__a, batch_size=args.train_batch_size ) SCREAMING_SNAKE_CASE_ = TensorDataset(*__a ) SCREAMING_SNAKE_CASE_ = SequentialSampler(__a ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, sampler=__a, batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: SCREAMING_SNAKE_CASE_ = args.max_steps SCREAMING_SNAKE_CASE_ = args.max_steps // (len(__a ) // args.gradient_accumulation_steps) + 1 else: SCREAMING_SNAKE_CASE_ = len(__a ) // args.gradient_accumulation_steps * args.num_train_epochs SCREAMING_SNAKE_CASE_ = list(model.named_parameters() ) SCREAMING_SNAKE_CASE_ = ['''bias''', '''LayerNorm.bias''', '''LayerNorm.weight'''] SCREAMING_SNAKE_CASE_ = [ { '''params''': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], '''weight_decay''': args.weight_decay, }, {'''params''': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], '''weight_decay''': 0.0}, ] SCREAMING_SNAKE_CASE_ = AdamW(__a, lr=args.learning_rate, eps=args.adam_epsilon ) SCREAMING_SNAKE_CASE_ = get_linear_schedule_with_warmup( __a, num_warmup_steps=args.warmup_steps, num_training_steps=__a ) if args.do_train: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ), desc='''Epoch''' ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = tqdm(__a, desc='''Training''' ) for step, batch in enumerate(__a ): SCREAMING_SNAKE_CASE_ = tuple(t.to(__a ) for t in batch ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = batch SCREAMING_SNAKE_CASE_ = model(__a, mc_token_ids=__a, lm_labels=__a, mc_labels=__a ) SCREAMING_SNAKE_CASE_ = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() SCREAMING_SNAKE_CASE_ = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 SCREAMING_SNAKE_CASE_ = '''Training loss: {:.2e} lr: {:.2e}'''.format(__a, scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer SCREAMING_SNAKE_CASE_ = model.module if hasattr(__a, '''module''' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` SCREAMING_SNAKE_CASE_ = os.path.join(args.output_dir, __a ) SCREAMING_SNAKE_CASE_ = os.path.join(args.output_dir, __a ) torch.save(model_to_save.state_dict(), __a ) model_to_save.config.to_json_file(__a ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned SCREAMING_SNAKE_CASE_ = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) SCREAMING_SNAKE_CASE_ = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(__a ) if args.do_eval: model.eval() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = 0, 0 SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = 0, 0 for batch in tqdm(__a, desc='''Evaluating''' ): SCREAMING_SNAKE_CASE_ = tuple(t.to(__a ) for t in batch ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = batch with torch.no_grad(): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = model( __a, mc_token_ids=__a, lm_labels=__a, mc_labels=__a ) SCREAMING_SNAKE_CASE_ = mc_logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE_ = mc_labels.to('''cpu''' ).numpy() SCREAMING_SNAKE_CASE_ = accuracy(__a, __a ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 SCREAMING_SNAKE_CASE_ = eval_loss / nb_eval_steps SCREAMING_SNAKE_CASE_ = eval_accuracy / nb_eval_examples SCREAMING_SNAKE_CASE_ = tr_loss / nb_tr_steps if args.do_train else None SCREAMING_SNAKE_CASE_ = {'''eval_loss''': eval_loss, '''eval_accuracy''': eval_accuracy, '''train_loss''': train_loss} SCREAMING_SNAKE_CASE_ = os.path.join(args.output_dir, '''eval_results.txt''' ) with open(__a, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key in sorted(result.keys() ): logger.info(''' %s = %s''', __a, str(result[key] ) ) writer.write('''%s = %s\n''' % (key, str(result[key] )) ) if __name__ == "__main__": main()
628
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class snake_case ( __lowercase ): UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_="cls" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = project_dim SCREAMING_SNAKE_CASE_ = pooler_fn SCREAMING_SNAKE_CASE_ = learn_encoder SCREAMING_SNAKE_CASE_ = use_attention_mask class snake_case ( __lowercase ): UpperCAmelCase__ = [R'''pooler''', R'''logit_scale'''] UpperCAmelCase__ = [R'''position_ids''', R'''predictions.decoder.bias'''] UpperCAmelCase__ = '''roberta''' UpperCAmelCase__ = RobertaSeriesConfig def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = XLMRobertaModel(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = getattr(SCREAMING_SNAKE_CASE_ , '''has_pre_transformation''' , SCREAMING_SNAKE_CASE_ ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def _lowercase (self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE_ = self.base_model( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , position_ids=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=SCREAMING_SNAKE_CASE_ , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = outputs['''hidden_states'''][-2] SCREAMING_SNAKE_CASE_ = self.pre_LN(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.transformation_pre(SCREAMING_SNAKE_CASE_ ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE_ = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
628
1
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a, __a ): return (preds == labels).mean() @dataclass class snake_case : UpperCAmelCase__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class snake_case : UpperCAmelCase__ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) UpperCAmelCase__ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) UpperCAmelCase__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def _lowerCamelCase ( ): # 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() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1 ), training_args.fpaa, ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''', __a ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE_ = processors[data_args.task_name]() SCREAMING_SNAKE_CASE_ = processor.get_labels() SCREAMING_SNAKE_CASE_ = len(__a ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=__a, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=__a, cache_dir=model_args.cache_dir, ) # Get datasets SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, ) if training_args.do_eval else None ) def compute_metrics(__a ) -> Dict: SCREAMING_SNAKE_CASE_ = np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(__a, p.label_ids )} # Data collator SCREAMING_SNAKE_CASE_ = DataCollatorWithPadding(__a, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE_ = Trainer( model=__a, args=__a, train_dataset=__a, eval_dataset=__a, compute_metrics=__a, data_collator=__a, ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ = trainer.evaluate() SCREAMING_SNAKE_CASE_ = os.path.join(training_args.output_dir, '''eval_results.txt''' ) if trainer.is_world_master(): with open(__a, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''', __a, __a ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__a ) return results def _lowerCamelCase ( __a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
628
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _lowerCamelCase ( __a, __a=0.9_9_9, __a="cosine", ): if alpha_transform_type == "cosine": def alpha_bar_fn(__a ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__a ): return math.exp(t * -1_2.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) SCREAMING_SNAKE_CASE_ = [] for i in range(__a ): SCREAMING_SNAKE_CASE_ = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__a ) / alpha_bar_fn(__a ), __a ) ) return torch.tensor(__a, dtype=torch.floataa ) class snake_case ( __lowercase , __lowercase ): UpperCAmelCase__ = [e.name for e in KarrasDiffusionSchedulers] UpperCAmelCase__ = 2 @register_to_config def __init__(self , SCREAMING_SNAKE_CASE_ = 10_00 , SCREAMING_SNAKE_CASE_ = 0.0_00_85 , SCREAMING_SNAKE_CASE_ = 0.0_12 , SCREAMING_SNAKE_CASE_ = "linear" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "epsilon" , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = "linspace" , SCREAMING_SNAKE_CASE_ = 0 , ): """simple docstring""" if trained_betas is not None: SCREAMING_SNAKE_CASE_ = torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE_ = torch.linspace(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) SCREAMING_SNAKE_CASE_ = 1.0 - self.betas SCREAMING_SNAKE_CASE_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = use_karras_sigmas def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" if schedule_timesteps is None: SCREAMING_SNAKE_CASE_ = self.timesteps SCREAMING_SNAKE_CASE_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: SCREAMING_SNAKE_CASE_ = 1 if len(SCREAMING_SNAKE_CASE_ ) > 1 else 0 else: SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep SCREAMING_SNAKE_CASE_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self ): """simple docstring""" if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = num_inference_steps SCREAMING_SNAKE_CASE_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": SCREAMING_SNAKE_CASE_ = np.linspace(0 , num_train_timesteps - 1 , SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )[::-1].copy() elif self.config.timestep_spacing == "leading": SCREAMING_SNAKE_CASE_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(0 , SCREAMING_SNAKE_CASE_ ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": SCREAMING_SNAKE_CASE_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(SCREAMING_SNAKE_CASE_ , 0 , -step_ratio )).round().copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps -= 1 else: raise ValueError( f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) SCREAMING_SNAKE_CASE_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.interp(SCREAMING_SNAKE_CASE_ , np.arange(0 , len(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) if self.config.use_karras_sigmas: SCREAMING_SNAKE_CASE_ = self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE_ , num_inference_steps=self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for sigma in sigmas] ) SCREAMING_SNAKE_CASE_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = timesteps.to(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = timesteps.to(device=SCREAMING_SNAKE_CASE_ ) # empty dt and derivative SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter SCREAMING_SNAKE_CASE_ = defaultdict(SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) # get distribution SCREAMING_SNAKE_CASE_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range SCREAMING_SNAKE_CASE_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) SCREAMING_SNAKE_CASE_ = low_idx + 1 SCREAMING_SNAKE_CASE_ = log_sigmas[low_idx] SCREAMING_SNAKE_CASE_ = log_sigmas[high_idx] # interpolate sigmas SCREAMING_SNAKE_CASE_ = (low - log_sigma) / (low - high) SCREAMING_SNAKE_CASE_ = np.clip(SCREAMING_SNAKE_CASE_ , 0 , 1 ) # transform interpolation to time range SCREAMING_SNAKE_CASE_ = (1 - w) * low_idx + w * high_idx SCREAMING_SNAKE_CASE_ = t.reshape(sigma.shape ) return t def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = in_sigmas[-1].item() SCREAMING_SNAKE_CASE_ = in_sigmas[0].item() SCREAMING_SNAKE_CASE_ = 7.0 # 7.0 is the value used in the paper SCREAMING_SNAKE_CASE_ = np.linspace(0 , 1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = sigma_min ** (1 / rho) SCREAMING_SNAKE_CASE_ = sigma_max ** (1 / rho) SCREAMING_SNAKE_CASE_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self ): """simple docstring""" return self.dt is None def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) # advance index counter by 1 SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = self.sigmas[step_index - 1] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE_ = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: SCREAMING_SNAKE_CASE_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep SCREAMING_SNAKE_CASE_ = sigma_next - sigma_hat # store for 2nd order step SCREAMING_SNAKE_CASE_ = derivative SCREAMING_SNAKE_CASE_ = dt SCREAMING_SNAKE_CASE_ = sample else: # 2. 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_next SCREAMING_SNAKE_CASE_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample SCREAMING_SNAKE_CASE_ = self.dt SCREAMING_SNAKE_CASE_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE_ ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = [self.index_for_timestep(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for t in timesteps] SCREAMING_SNAKE_CASE_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): SCREAMING_SNAKE_CASE_ = sigma.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_ = original_samples + noise * sigma return noisy_samples def __len__(self ): """simple docstring""" return self.config.num_train_timesteps
628
1
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a, __a ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_ = BigBirdConfig.from_json_file(__a ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: SCREAMING_SNAKE_CASE_ = BigBirdForQuestionAnswering(__a ) else: SCREAMING_SNAKE_CASE_ = BigBirdForPreTraining(__a ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__a, __a, is_trivia_qa=__a ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) 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( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
628
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = 8 # DPR tok SCREAMING_SNAKE_CASE_ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , DPR_VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) # BART tok SCREAMING_SNAKE_CASE_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE_ = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''bart_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self ): """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''bart_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''custom''' , ) if from_disk: SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dataset''' ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''index.faiss''' ) dataset.get_index('''embeddings''' ).save(os.path.join(self.tmpdirname , '''index.faiss''' ) ) dataset.drop_index('''embeddings''' ) dataset.save_to_disk(os.path.join(self.tmpdirname , '''dataset''' ) ) del dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , SCREAMING_SNAKE_CASE_ ) , ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''hf_bert_base.hnswSQ8_correct_phi_128.c_index''' ) dataset.save_faiss_index('''embeddings''' , index_file_name + '''.index.dpr''' ) pickle.dump(dataset['''id'''] , open(index_file_name + '''.index_meta.dpr''' , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''psgs_w100.tsv.pkl''' ) SCREAMING_SNAKE_CASE_ = {sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset} pickle.dump(SCREAMING_SNAKE_CASE_ , open(SCREAMING_SNAKE_CASE_ , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''legacy''' , index_path=self.tmpdirname , ) SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''text'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''text'''][0] , '''bar''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''text'''][0] , '''foo''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) SCREAMING_SNAKE_CASE_ = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( # noqa: F841 out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], out['''doc_ids'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dpr_ctx_encoder_tokenizer() SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) retriever.set_ctx_encoder_tokenizer(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual( len(SCREAMING_SNAKE_CASE_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''') ) , SCREAMING_SNAKE_CASE_ ) # check for doc token related keys in dictionary.
628
1
"""simple docstring""" from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration lowerCAmelCase__ = HfArgumentParser(InitializationArguments) lowerCAmelCase__ = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization lowerCAmelCase__ = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks lowerCAmelCase__ = { 'vocab_size': len(tokenizer), 'scale_attn_by_inverse_layer_idx': True, 'reorder_and_upcast_attn': True, } # Load model config (GPT-2 large in this case) lowerCAmelCase__ = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config lowerCAmelCase__ = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
628
"""simple docstring""" from collections.abc import Sequence from queue import Queue class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = start SCREAMING_SNAKE_CASE_ = end SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = left SCREAMING_SNAKE_CASE_ = right def __repr__(self ): """simple docstring""" return f'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = collection SCREAMING_SNAKE_CASE_ = function if self.collection: SCREAMING_SNAKE_CASE_ = self._build_tree(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self._update_tree(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self._query_range(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.collection[start] ) SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = self._build_tree(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE_ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == i: SCREAMING_SNAKE_CASE_ = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.fn(node.left.val , node.right.val ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE_ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE_ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" if self.root is not None: SCREAMING_SNAKE_CASE_ = Queue() queue.put(self.root ) while not queue.empty(): SCREAMING_SNAKE_CASE_ = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('*' * 50) lowerCAmelCase__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
628
1
"""simple docstring""" def _lowerCamelCase ( __a ): if isinstance(__a, __a ): raise TypeError('''\'float\' object cannot be interpreted as an integer''' ) if isinstance(__a, __a ): raise TypeError('''\'str\' object cannot be interpreted as an integer''' ) if num == 0: return "0b0" SCREAMING_SNAKE_CASE_ = False if num < 0: SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = -num SCREAMING_SNAKE_CASE_ = [] while num > 0: binary.insert(0, num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(__a ) for e in binary ) return "0b" + "".join(str(__a ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
628
"""simple docstring""" def _lowerCamelCase ( __a ): if not isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be an integer' raise TypeError(__a ) if number < 1: SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be > 0' raise ValueError(__a ) SCREAMING_SNAKE_CASE_ = 1 for i in range(1, __a ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
628
1
"""simple docstring""" import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class snake_case ( __lowercase ): UpperCAmelCase__ = (KDPMaDiscreteScheduler,) UpperCAmelCase__ = 10 def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = { '''num_train_timesteps''': 11_00, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _lowercase (self ): """simple docstring""" for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] , [0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = self.dummy_model() SCREAMING_SNAKE_CASE_ = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE_ = sample.to(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE_ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = output.prev_sample SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6_9_3_4e-0_7 ) < 1e-2 assert abs(result_mean.item() - 6.1_1_1_2e-1_0 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 4.6_9_3_4_2_8_6_5_0_1_7_0_9_7_2e-0_7 ) < 1e-2 assert abs(result_mean.item() - 0.00_02 ) < 1e-3 def _lowercase (self ): """simple docstring""" if torch_device == "mps": return SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = self.dummy_model() SCREAMING_SNAKE_CASE_ = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE_ = sample.to(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE_ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = output.prev_sample SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3 def _lowercase (self ): """simple docstring""" if torch_device == "mps": return SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.dummy_model() SCREAMING_SNAKE_CASE_ = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = output.prev_sample SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.41_25 ) < 1e-2 assert abs(result_mean.item() - 0.02_66 ) < 1e-3
628
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = len(__a ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: SCREAMING_SNAKE_CASE_ = i + 1 else: SCREAMING_SNAKE_CASE_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f'''{two_pointer([2, 7, 11, 15], 9) = }''')
628
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
628
"""simple docstring""" import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a=2, __a=3, __a=16, __a = 10, __a = 2 ): def get_dataset(__a ): SCREAMING_SNAKE_CASE_ = torch.randn(batch_size * n_batches, 1 ) return TensorDataset(__a, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1 ) ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) return (train_dataloader, valid_dataloader) def _lowerCamelCase ( __a, __a, __a, __a, __a, __a=None ): SCREAMING_SNAKE_CASE_ = [] for epoch in range(__a ): # Train quickly model.train() for batch in dataloader: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = batch SCREAMING_SNAKE_CASE_ = model(__a ) SCREAMING_SNAKE_CASE_ = torch.nn.functional.mse_loss(__a, __a ) accelerator.backward(__a ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class snake_case ( nn.Module ): def __init__(self ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return x * self.a + self.b class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(total_limit=1 , project_dir=SCREAMING_SNAKE_CASE_ , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''initial''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoint''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) # Load everything back in and make sure all states work accelerator.load_state(SCREAMING_SNAKE_CASE_ ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_1''' ) ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch.tensor([1, 2, 3] ) SCREAMING_SNAKE_CASE_ = torch.tensor([2, 3, 4] ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(net.parameters() ) SCREAMING_SNAKE_CASE_ = Accelerator() with self.assertRaises(SCREAMING_SNAKE_CASE_ ) as ve: accelerator.register_for_checkpointing(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = str(ve.exception ) self.assertTrue('''Item at index 0''' in message ) self.assertTrue('''Item at index 1''' in message ) self.assertFalse('''Item at index 2''' in message ) self.assertFalse('''Item at index 3''' in message ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ = torch.optim.lr_scheduler.StepLR(SCREAMING_SNAKE_CASE_ , step_size=1 , gamma=0.99 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() SCREAMING_SNAKE_CASE_ = scheduler.state_dict() train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) self.assertEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ , total_limit=2 ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_9''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_10''' ) ) ) @require_cuda def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() ) if __name__ == "__main__": lowerCAmelCase__ = '/tmp/accelerate/state_checkpointing' lowerCAmelCase__ = DummyModel() lowerCAmelCase__ = torch.optim.Adam(params=model.parameters(), lr=1e-3) lowerCAmelCase__ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) lowerCAmelCase__, lowerCAmelCase__ = dummy_dataloaders() lowerCAmelCase__ = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline lowerCAmelCase__ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert param_device.type == accelerator.device.type lowerCAmelCase__ = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
628
1
"""simple docstring""" from random import randint, random def _lowerCamelCase ( __a, __a, __a, __a = False, __a = False, __a = 5, ): SCREAMING_SNAKE_CASE_ = [[-1] * number_of_cells] # Create a highway without any car SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = max(__a, 0 ) while i < number_of_cells: SCREAMING_SNAKE_CASE_ = ( randint(0, __a ) if random_speed else initial_speed ) # Place the cars i += ( randint(1, max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = highway_now[car_index + 1 :] for cell in range(len(__a ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(__a, -1 ) def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = len(__a ) # Beforce calculations, the highway is empty SCREAMING_SNAKE_CASE_ = [-1] * number_of_cells for car_index in range(__a ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed SCREAMING_SNAKE_CASE_ = min(highway_now[car_index] + 1, __a ) # Number of empty cell before the next car SCREAMING_SNAKE_CASE_ = get_distance(__a, __a ) - 1 # We can't have the car causing an accident SCREAMING_SNAKE_CASE_ = min(next_highway[car_index], __a ) if random() < probability: # Randomly, a driver will slow down SCREAMING_SNAKE_CASE_ = max(next_highway[car_index] - 1, 0 ) return next_highway def _lowerCamelCase ( __a, __a, __a, __a ): SCREAMING_SNAKE_CASE_ = len(highway[0] ) for i in range(__a ): SCREAMING_SNAKE_CASE_ = update(highway[i], __a, __a ) SCREAMING_SNAKE_CASE_ = [-1] * number_of_cells for car_index in range(__a ): SCREAMING_SNAKE_CASE_ = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) SCREAMING_SNAKE_CASE_ = (car_index + speed) % number_of_cells # Commit the change of position SCREAMING_SNAKE_CASE_ = speed highway.append(__a ) return highway if __name__ == "__main__": import doctest doctest.testmod()
628
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class snake_case ( __lowercase ): UpperCAmelCase__ = (DDIMParallelScheduler,) UpperCAmelCase__ = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def _lowercase (self ): """simple docstring""" for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def _lowercase (self ): """simple docstring""" for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , sample_max_value=SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.1_47_71 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.3_24_60 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = 10, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE_ = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 11_47.79_04 ) < 1e-2 assert abs(result_mean.item() - 0.49_82 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop() SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_72.00_67 ) < 1e-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 52.53_02 ) < 1e-2 assert abs(result_mean.item() - 0.06_84 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.82_95 ) < 1e-2 assert abs(result_mean.item() - 0.19_51 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.07_84 ) < 1e-2 assert abs(result_mean.item() - 0.19_41 ) < 1e-3
628
1
"""simple docstring""" def _lowerCamelCase ( __a = 4_000_000 ): SCREAMING_SNAKE_CASE_ = [0, 1] SCREAMING_SNAKE_CASE_ = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 SCREAMING_SNAKE_CASE_ = 0 for j in range(len(__a ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f'''{solution() = }''')
628
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = TransfoXLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''<unk> UNwanted , running''' SCREAMING_SNAKE_CASE_ = '''<unk> unwanted, running''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [0, 4, 8, 7] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' SCREAMING_SNAKE_CASE_ = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = len(SCREAMING_SNAKE_CASE_ ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
628
1
"""simple docstring""" import logging import os from .state import PartialState class snake_case ( logging.LoggerAdapter ): @staticmethod def _lowercase (SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''main_process_only''' , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''in_order''' , SCREAMING_SNAKE_CASE_ ) if self.isEnabledFor(SCREAMING_SNAKE_CASE_ ): if self._should_log(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) elif in_order: SCREAMING_SNAKE_CASE_ = PartialState() for i in range(state.num_processes ): if i == state.process_index: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = self.process(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.logger.log(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) state.wait_for_everyone() def _lowerCamelCase ( __a, __a = None ): if log_level is None: SCREAMING_SNAKE_CASE_ = os.environ.get('''ACCELERATE_LOG_LEVEL''', __a ) SCREAMING_SNAKE_CASE_ = logging.getLogger(__a ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__a, {} )
628
"""simple docstring""" from __future__ import annotations import typing from collections import Counter def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__a, max_perimeter + 1 ): SCREAMING_SNAKE_CASE_ = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__a ): SCREAMING_SNAKE_CASE_ = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _lowerCamelCase ( __a = 1_000 ): SCREAMING_SNAKE_CASE_ = pythagorean_triple(__a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
628
1
"""simple docstring""" def _lowerCamelCase ( __a = 1_000_000 ): SCREAMING_SNAKE_CASE_ = [i - 1 for i in range(limit + 1 )] for i in range(2, limit + 1 ): if phi[i] == i - 1: for j in range(2 * i, limit + 1, __a ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
628
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _lowerCamelCase ( __a ): if is_torch_version('''<''', '''2.0.0''' ) or not hasattr(__a, '''_dynamo''' ): return False return isinstance(__a, torch._dynamo.eval_frame.OptimizedModule ) def _lowerCamelCase ( __a, __a = True ): SCREAMING_SNAKE_CASE_ = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE_ = is_compiled_module(__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE_ = getattr(__a, '''forward''' ) SCREAMING_SNAKE_CASE_ = model.__dict__.pop('''_original_forward''', __a ) if original_forward is not None: while hasattr(__a, '''__wrapped__''' ): SCREAMING_SNAKE_CASE_ = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE_ = forward if getattr(__a, '''_converted_to_transformer_engine''', __a ): convert_model(__a, to_transformer_engine=__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = compiled_model return model def _lowerCamelCase ( ): PartialState().wait_for_everyone() def _lowerCamelCase ( __a, __a ): if PartialState().distributed_type == DistributedType.TPU: xm.save(__a, __a ) elif PartialState().local_process_index == 0: torch.save(__a, __a ) @contextmanager def _lowerCamelCase ( **__a ): for key, value in kwargs.items(): SCREAMING_SNAKE_CASE_ = str(__a ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _lowerCamelCase ( __a ): if not hasattr(__a, '''__qualname__''' ) and not hasattr(__a, '''__name__''' ): SCREAMING_SNAKE_CASE_ = getattr(__a, '''__class__''', __a ) if hasattr(__a, '''__qualname__''' ): return obj.__qualname__ if hasattr(__a, '''__name__''' ): return obj.__name__ return str(__a ) def _lowerCamelCase ( __a, __a ): for key, value in source.items(): if isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = destination.setdefault(__a, {} ) merge_dicts(__a, __a ) else: SCREAMING_SNAKE_CASE_ = value return destination def _lowerCamelCase ( __a = None ): if port is None: SCREAMING_SNAKE_CASE_ = 29_500 with socket.socket(socket.AF_INET, socket.SOCK_STREAM ) as s: return s.connect_ex(('''localhost''', port) ) == 0
628
1
"""simple docstring""" import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''hidden_sizes''' ) ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''num_attention_heads''' ) ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''num_encoder_blocks''' ) ) class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[8, 4, 2, 1] , SCREAMING_SNAKE_CASE_=[16, 32, 64, 1_28] , SCREAMING_SNAKE_CASE_=[1, 4, 8, 16] , SCREAMING_SNAKE_CASE_=[1, 2, 4, 8] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = parent SCREAMING_SNAKE_CASE_ = batch_size SCREAMING_SNAKE_CASE_ = image_size SCREAMING_SNAKE_CASE_ = num_channels SCREAMING_SNAKE_CASE_ = num_encoder_blocks SCREAMING_SNAKE_CASE_ = sr_ratios SCREAMING_SNAKE_CASE_ = depths SCREAMING_SNAKE_CASE_ = hidden_sizes SCREAMING_SNAKE_CASE_ = downsampling_rates SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = is_training SCREAMING_SNAKE_CASE_ = use_labels SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = hidden_dropout_prob SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = num_labels SCREAMING_SNAKE_CASE_ = scope def _lowercase (self ): """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.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE_ = self.get_config() return config, pixel_values, labels def _lowercase (self ): """simple docstring""" return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = SegformerModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = SCREAMING_SNAKE_CASE_ = self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.num_labels SCREAMING_SNAKE_CASE_ = SegformerForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = SegformerForSemanticSegmentation(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE_ = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertGreater(result.loss , 0.0 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = config_and_inputs SCREAMING_SNAKE_CASE_ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class snake_case ( __lowercase , __lowercase , unittest.TestCase ): UpperCAmelCase__ = ( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) UpperCAmelCase__ = ( { '''feature-extraction''': SegformerModel, '''image-classification''': SegformerForImageClassification, '''image-segmentation''': SegformerForSemanticSegmentation, } if is_torch_available() else {} ) UpperCAmelCase__ = True UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = SegformerModelTester(self ) SCREAMING_SNAKE_CASE_ = SegformerConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" self.config_tester.run_common_tests() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*SCREAMING_SNAKE_CASE_ ) @unittest.skip('''SegFormer does not use inputs_embeds''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''SegFormer does not have get_input_embeddings method and get_output_embeddings methods''' ) def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """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(SCREAMING_SNAKE_CASE_ ) 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] , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ = True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = outputs.attentions SCREAMING_SNAKE_CASE_ = sum(self.model_tester.depths ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) # verify the first attentions (first block, first layer) SCREAMING_SNAKE_CASE_ = (self.model_tester.image_size // 4) ** 2 SCREAMING_SNAKE_CASE_ = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) SCREAMING_SNAKE_CASE_ = (self.model_tester.image_size // 32) ** 2 SCREAMING_SNAKE_CASE_ = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) SCREAMING_SNAKE_CASE_ = len(SCREAMING_SNAKE_CASE_ ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) # verify the first attentions (first block, first layer) SCREAMING_SNAKE_CASE_ = (self.model_tester.image_size // 4) ** 2 SCREAMING_SNAKE_CASE_ = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def _lowercase (self ): """simple docstring""" def check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = outputs.hidden_states SCREAMING_SNAKE_CASE_ = self.model_tester.num_encoder_blocks self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) 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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ = True for model_class in self.all_model_classes: if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue SCREAMING_SNAKE_CASE_ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() SCREAMING_SNAKE_CASE_ = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def _lowercase (self ): """simple docstring""" pass @slow def _lowercase (self ): """simple docstring""" for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ = SegformerModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch class snake_case ( unittest.TestCase ): @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=SCREAMING_SNAKE_CASE_ , align=SCREAMING_SNAKE_CASE_ , do_random_crop=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512''' ).to( SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.Size((1, model.config.num_labels, 1_28, 1_28) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.tensor( [ [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]], [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]], [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]], ] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) ) @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=SCREAMING_SNAKE_CASE_ , align=SCREAMING_SNAKE_CASE_ , do_random_crop=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = SegformerForSemanticSegmentation.from_pretrained( '''nvidia/segformer-b1-finetuned-cityscapes-1024-1024''' ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.Size((1, model.config.num_labels, 1_28, 1_28) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.tensor( [ [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]], [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]], [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]], ] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-1 ) ) @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=SCREAMING_SNAKE_CASE_ , align=SCREAMING_SNAKE_CASE_ , do_random_crop=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512''' ).to( SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = encoded_inputs.pixel_values.to(SCREAMING_SNAKE_CASE_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE_ = image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_ , target_sizes=[(5_00, 3_00)] ) SCREAMING_SNAKE_CASE_ = torch.Size((5_00, 3_00) ) self.assertEqual(segmentation[0].shape , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.Size((1_28, 1_28) ) self.assertEqual(segmentation[0].shape , SCREAMING_SNAKE_CASE_ )
628
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = CTRLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE_ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
628
1
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class snake_case : pass
628
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a, __a ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_ = BigBirdConfig.from_json_file(__a ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: SCREAMING_SNAKE_CASE_ = BigBirdForQuestionAnswering(__a ) else: SCREAMING_SNAKE_CASE_ = BigBirdForPreTraining(__a ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__a, __a, is_trivia_qa=__a ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) 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( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
628
1
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class snake_case ( unittest.TestCase ): @parameterized.expand([(None,), ('''foo.json''',)] ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained('''gpt2''' ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = GenerationConfig() SCREAMING_SNAKE_CASE_ = { '''max_new_tokens''': 10_24, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = generation_config.update(**SCREAMING_SNAKE_CASE_ ) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 10_24 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = GenerationConfig() SCREAMING_SNAKE_CASE_ = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(default_config.num_beams , 1 ) SCREAMING_SNAKE_CASE_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class snake_case ( unittest.TestCase ): @classmethod def _lowercase (cls ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def _lowercase (cls ): """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_pretrained(f'{USER}/test-generation-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_pretrained(f'{USER}/test-generation-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE_ = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
628
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name def _lowerCamelCase ( __a ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''', __a, ) if isinstance(__a, torch.Tensor ): return image elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [image] if isinstance(image[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = image[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE_ = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = np.array(__a ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = image.transpose(0, 3, 1, 2 ) SCREAMING_SNAKE_CASE_ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(image[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return image def _lowerCamelCase ( __a ): if isinstance(__a, torch.Tensor ): return mask elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [mask] if isinstance(mask[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = mask[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE_ = [np.array(m.convert('''L''' ).resize((w, h), resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(mask[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return mask class snake_case ( __lowercase ): UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 2_50 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = image SCREAMING_SNAKE_CASE_ = _preprocess_image(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = _preprocess_mask(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE_ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) SCREAMING_SNAKE_CASE_ = original_image.shape SCREAMING_SNAKE_CASE_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) SCREAMING_SNAKE_CASE_ = eta SCREAMING_SNAKE_CASE_ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE_ = generator[0] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE_ = self.scheduler.undo_step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = t SCREAMING_SNAKE_CASE_ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
628
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class snake_case ( __lowercase ): UpperCAmelCase__ = '''sew-d''' def __init__(self , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=30_72 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=("p2c", "c2p") , SCREAMING_SNAKE_CASE_="layer_norm" , SCREAMING_SNAKE_CASE_="gelu_python" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-7 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_="group" , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=(64, 1_28, 1_28, 1_28, 1_28, 2_56, 2_56, 2_56, 2_56, 5_12, 5_12, 5_12, 5_12) , SCREAMING_SNAKE_CASE_=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE_=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1_28 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.05 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="mean" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = hidden_size SCREAMING_SNAKE_CASE_ = feat_extract_norm SCREAMING_SNAKE_CASE_ = feat_extract_activation SCREAMING_SNAKE_CASE_ = list(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = list(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = list(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = conv_bias SCREAMING_SNAKE_CASE_ = num_conv_pos_embeddings SCREAMING_SNAKE_CASE_ = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE_ = len(self.conv_dim ) SCREAMING_SNAKE_CASE_ = num_hidden_layers SCREAMING_SNAKE_CASE_ = intermediate_size SCREAMING_SNAKE_CASE_ = squeeze_factor SCREAMING_SNAKE_CASE_ = max_position_embeddings SCREAMING_SNAKE_CASE_ = position_buckets SCREAMING_SNAKE_CASE_ = share_att_key SCREAMING_SNAKE_CASE_ = relative_attention SCREAMING_SNAKE_CASE_ = norm_rel_ebd SCREAMING_SNAKE_CASE_ = list(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = hidden_dropout SCREAMING_SNAKE_CASE_ = attention_dropout SCREAMING_SNAKE_CASE_ = activation_dropout SCREAMING_SNAKE_CASE_ = feat_proj_dropout SCREAMING_SNAKE_CASE_ = final_dropout SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = feature_layer_norm_eps SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect.''' '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,''' f'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' f'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE_ = apply_spec_augment SCREAMING_SNAKE_CASE_ = mask_time_prob SCREAMING_SNAKE_CASE_ = mask_time_length SCREAMING_SNAKE_CASE_ = mask_time_min_masks SCREAMING_SNAKE_CASE_ = mask_feature_prob SCREAMING_SNAKE_CASE_ = mask_feature_length SCREAMING_SNAKE_CASE_ = mask_feature_min_masks # ctc loss SCREAMING_SNAKE_CASE_ = ctc_loss_reduction SCREAMING_SNAKE_CASE_ = ctc_zero_infinity # sequence classification SCREAMING_SNAKE_CASE_ = use_weighted_layer_sum SCREAMING_SNAKE_CASE_ = classifier_proj_size @property def _lowercase (self ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
628
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a, __a ): return (preds == labels).mean() @dataclass class snake_case : UpperCAmelCase__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class snake_case : UpperCAmelCase__ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) UpperCAmelCase__ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) UpperCAmelCase__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def _lowerCamelCase ( ): # 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() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1 ), training_args.fpaa, ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''', __a ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE_ = processors[data_args.task_name]() SCREAMING_SNAKE_CASE_ = processor.get_labels() SCREAMING_SNAKE_CASE_ = len(__a ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=__a, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=__a, cache_dir=model_args.cache_dir, ) # Get datasets SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, ) if training_args.do_eval else None ) def compute_metrics(__a ) -> Dict: SCREAMING_SNAKE_CASE_ = np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(__a, p.label_ids )} # Data collator SCREAMING_SNAKE_CASE_ = DataCollatorWithPadding(__a, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE_ = Trainer( model=__a, args=__a, train_dataset=__a, eval_dataset=__a, compute_metrics=__a, data_collator=__a, ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ = trainer.evaluate() SCREAMING_SNAKE_CASE_ = os.path.join(training_args.output_dir, '''eval_results.txt''' ) if trainer.is_world_master(): with open(__a, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''', __a, __a ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__a ) return results def _lowerCamelCase ( __a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
628
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCAmelCase__ = { "configuration_longt5": ["LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongT5Config", "LongT5OnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ "LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST", "LongT5EncoderModel", "LongT5ForConditionalGeneration", "LongT5Model", "LongT5PreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ "FlaxLongT5ForConditionalGeneration", "FlaxLongT5Model", "FlaxLongT5PreTrainedModel", ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
700
"""simple docstring""" import cva import numpy as np class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if k in (0.04, 0.06): SCREAMING_SNAKE_CASE_ = k SCREAMING_SNAKE_CASE_ = window_size else: raise ValueError('''invalid k value''' ) def __str__(self ): """simple docstring""" return str(self.k ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = cva.imread(SCREAMING_SNAKE_CASE_ , 0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = img.shape SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = img.copy() SCREAMING_SNAKE_CASE_ = cva.cvtColor(SCREAMING_SNAKE_CASE_ , cva.COLOR_GRAY2RGB ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = np.gradient(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = dx**2 SCREAMING_SNAKE_CASE_ = dy**2 SCREAMING_SNAKE_CASE_ = dx * dy SCREAMING_SNAKE_CASE_ = 0.04 SCREAMING_SNAKE_CASE_ = self.window_size // 2 for y in range(SCREAMING_SNAKE_CASE_ , h - offset ): for x in range(SCREAMING_SNAKE_CASE_ , w - offset ): SCREAMING_SNAKE_CASE_ = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = (wxx * wyy) - (wxy**2) SCREAMING_SNAKE_CASE_ = wxx + wyy SCREAMING_SNAKE_CASE_ = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": lowerCAmelCase__ = HarrisCorner(0.04, 3) lowerCAmelCase__, lowerCAmelCase__ = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
628
0
"""simple docstring""" import numpy as np from PIL import Image def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = np.array(__A ) 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 _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = np.array(__A ) 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()
701
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class snake_case ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.text_to_image( prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = pipe.image_variation(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
628
0
import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = ['model.decoder.embed_positions.weights'] def _lowerCamelCase ( __a ): if "emb" in name: SCREAMING_SNAKE_CASE_ = name.replace('''emb''', '''model.decoder.embed_tokens''' ) if "transformer" in name: SCREAMING_SNAKE_CASE_ = name.replace('''transformer''', '''model.decoder''' ) if "cross_attention" in name: SCREAMING_SNAKE_CASE_ = name.replace('''cross_attention''', '''encoder_attn''' ) if "linear1" in name: SCREAMING_SNAKE_CASE_ = name.replace('''linear1''', '''fc1''' ) if "linear2" in name: SCREAMING_SNAKE_CASE_ = name.replace('''linear2''', '''fc2''' ) if "norm1" in name: SCREAMING_SNAKE_CASE_ = name.replace('''norm1''', '''self_attn_layer_norm''' ) if "norm_cross" in name: SCREAMING_SNAKE_CASE_ = name.replace('''norm_cross''', '''encoder_attn_layer_norm''' ) if "norm2" in name: SCREAMING_SNAKE_CASE_ = name.replace('''norm2''', '''final_layer_norm''' ) if "out_norm" in name: SCREAMING_SNAKE_CASE_ = name.replace('''out_norm''', '''model.decoder.layer_norm''' ) if "linears" in name: SCREAMING_SNAKE_CASE_ = name.replace('''linears''', '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('''condition_provider.conditioners.description.output_proj''', '''enc_to_dec_proj''' ) return name def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = list(state_dict.keys() ) SCREAMING_SNAKE_CASE_ = {} for key in keys: SCREAMING_SNAKE_CASE_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj SCREAMING_SNAKE_CASE_ = val[:hidden_size, :] SCREAMING_SNAKE_CASE_ = val[hidden_size : 2 * hidden_size, :] SCREAMING_SNAKE_CASE_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: SCREAMING_SNAKE_CASE_ = val else: SCREAMING_SNAKE_CASE_ = val return state_dict, enc_dec_proj_state_dict def _lowerCamelCase ( __a ): if checkpoint == "small": # default config values SCREAMING_SNAKE_CASE_ = 1_024 SCREAMING_SNAKE_CASE_ = 24 SCREAMING_SNAKE_CASE_ = 16 elif checkpoint == "medium": SCREAMING_SNAKE_CASE_ = 1_536 SCREAMING_SNAKE_CASE_ = 48 SCREAMING_SNAKE_CASE_ = 24 elif checkpoint == "large": SCREAMING_SNAKE_CASE_ = 2_048 SCREAMING_SNAKE_CASE_ = 48 SCREAMING_SNAKE_CASE_ = 32 else: raise ValueError(F'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.' ) SCREAMING_SNAKE_CASE_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE, ffn_dim=hidden_size * 4, num_hidden_layers=_SCREAMING_SNAKE_CASE, num_attention_heads=_SCREAMING_SNAKE_CASE, ) return config @torch.no_grad() def _lowerCamelCase ( __a, __a=None, __a=None, __a="cpu" ): SCREAMING_SNAKE_CASE_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE, device=_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = fairseq_model.lm.state_dict() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = rename_state_dict( _SCREAMING_SNAKE_CASE, hidden_size=decoder_config.hidden_size ) SCREAMING_SNAKE_CASE_ = TaEncoderModel.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) SCREAMING_SNAKE_CASE_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE, strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F'Missing key(s) in state_dict: {missing_keys}' ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(F'Unexpected key(s) in state_dict: {unexpected_keys}' ) # init the composite model SCREAMING_SNAKE_CASE_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE, audio_encoder=_SCREAMING_SNAKE_CASE, decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass SCREAMING_SNAKE_CASE_ = torch.arange(0, 8, dtype=torch.long ).reshape(2, -1 ) SCREAMING_SNAKE_CASE_ = input_ids.reshape(2 * 4, -1 ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(input_ids=_SCREAMING_SNAKE_CASE, decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''t5-base''' ) SCREAMING_SNAKE_CASE_ = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''', padding_side='''left''' ) SCREAMING_SNAKE_CASE_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE, tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids SCREAMING_SNAKE_CASE_ = 2_048 SCREAMING_SNAKE_CASE_ = 2_048 # set other default generation config params SCREAMING_SNAKE_CASE_ = int(30 * audio_encoder.config.frame_rate ) SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(F'Saving model {checkpoint} to {pytorch_dump_folder}' ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(F'Pushing model {checkpoint} to {repo_id}' ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) lowerCAmelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
702
"""simple docstring""" import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def _lowerCamelCase ( __a ): # picklable for multiprocessing return x.sum() def _lowerCamelCase ( __a ): # picklable for multiprocessing return i + 1 @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = [1, 2] SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': [1, 2], '''b''': [3, 4]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 1}, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = [2, 3] SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': [2, 3], '''b''': [4, 5]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 2}, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = 2 self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = {'''a''': np.eye(2 ), '''b''': np.zeros(3 ), '''c''': np.ones(2 )} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 0, '''c''': 2} SCREAMING_SNAKE_CASE_ = { '''a''': np.eye(2 ).astype(SCREAMING_SNAKE_CASE_ ), '''b''': np.zeros(3 ).astype(SCREAMING_SNAKE_CASE_ ), '''c''': np.ones(2 ).astype(SCREAMING_SNAKE_CASE_ ), } self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): # can't pickle a local lambda map_nested(lambda SCREAMING_SNAKE_CASE_ : x + 1 , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 3, '''b''': 4} SCREAMING_SNAKE_CASE_ = {'''a''': 5, '''b''': 6} SCREAMING_SNAKE_CASE_ = sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" class snake_case : UpperCAmelCase__ = '''bar''' SCREAMING_SNAKE_CASE_ = Foo() self.assertEqual(foo.my_attr , '''bar''' ) with temporary_assignment(SCREAMING_SNAKE_CASE_ , '''my_attr''' , '''BAR''' ): self.assertEqual(foo.my_attr , '''BAR''' ) self.assertEqual(foo.my_attr , '''bar''' ) @pytest.mark.parametrize( '''iterable_length, num_proc, expected_num_proc''', [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ], ) def _lowerCamelCase ( __a, __a, __a ): with patch('''datasets.utils.py_utils._single_map_nested''' ) as mock_single_map_nested, patch( '''datasets.parallel.parallel.Pool''' ) as mock_multiprocessing_pool: SCREAMING_SNAKE_CASE_ = {F'{i}': i for i in range(__a )} SCREAMING_SNAKE_CASE_ = map_nested(lambda __a : x + 10, __a, num_proc=__a, parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class snake_case ( __lowercase ): @require_tf def _lowercase (self ): """simple docstring""" import tensorflow as tf from tensorflow.keras import layers SCREAMING_SNAKE_CASE_ = layers.Dense(2 ) def gen_random_output(): SCREAMING_SNAKE_CASE_ = tf.random.uniform((1, 3) ) return model(SCREAMING_SNAKE_CASE_ ).numpy() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def _lowercase (self ): """simple docstring""" import torch def gen_random_output(): SCREAMING_SNAKE_CASE_ = torch.nn.Linear(3 , 2 ) SCREAMING_SNAKE_CASE_ = torch.rand(1 , 3 ) return model(SCREAMING_SNAKE_CASE_ ).detach().numpy() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def _lowercase (self ): """simple docstring""" def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize('''input_data''', [{}] ) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).data assert output_data == input_data @pytest.mark.parametrize( '''data, expected_output''', [ ({}, []), ([], []), ('''foo''', ['''foo''']), (['''foo''', '''bar'''], ['''foo''', '''bar''']), ([['''foo''', '''bar''']], ['''foo''', '''bar''']), ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']), ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']), ({'''a''': 1, '''b''': 2}, [1, 2]), ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]), ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]), ], ) def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).flatten() assert output == expected_output def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = A(x=1, y='''foobar''' ) SCREAMING_SNAKE_CASE_ = {'''x''': 1, '''y''': '''foobar'''} assert asdict(__a ) == expected_output SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': A(x=10, y='''foo''' )}, '''c''': [A(x=20, y='''bar''' )]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]} assert asdict(__a ) == expected_output with pytest.raises(__a ): asdict([1, A(x=10, y='''foo''' )] ) def _lowerCamelCase ( __a ): return text.split() def _lowerCamelCase ( __a ): yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def _lowerCamelCase ( ): with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = [] for yield_time, content in iflatmap_unordered( __a, _aseconds_generator_of_aitems_with_timing, kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__a ) assert out.count('''a''' ) == 2 assert out.count('''b''' ) == 2 assert len(__a ) == 4
628
0
import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch lowerCAmelCase__ = "sshleifer/bart-tiny-random" lowerCAmelCase__ = "patrickvonplaten/t5-tiny-random" @require_torch class snake_case ( unittest.TestCase ): @cached_property def _lowercase (self ): """simple docstring""" return AutoConfig.from_pretrained(A_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ ,*SCREAMING_SNAKE_CASE_ = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.num_hidden_layers , 1 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ ,*SCREAMING_SNAKE_CASE_ = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=A_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ ,*SCREAMING_SNAKE_CASE_ = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=A_ ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ ,*SCREAMING_SNAKE_CASE_ = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , 1 ) def _lowercase (self ): """simple docstring""" with self.assertRaises(A_ ): create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=A_ , d=A_ )
703
"""simple docstring""" import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCAmelCase__ = { 'facebook/maskformer-swin-base-ade': ( 'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowerCAmelCase__ = logging.get_logger(__name__) class snake_case ( __lowercase ): UpperCAmelCase__ = '''maskformer''' UpperCAmelCase__ = {'''hidden_size''': '''mask_feature_size'''} UpperCAmelCase__ = ['''resnet''', '''swin'''] UpperCAmelCase__ = ['''detr'''] def __init__(self , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 20.0 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k SCREAMING_SNAKE_CASE_ = SwinConfig( image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = backbone_config.pop('''model_type''' ) SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ' f'Supported model types: {",".join(self.backbones_supported )}' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 SCREAMING_SNAKE_CASE_ = DetrConfig() else: # verify that the decoder is supported SCREAMING_SNAKE_CASE_ = ( decoder_config.pop('''model_type''' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'Transformer Decoder {decoder_type} not supported, please use one of' f' {",".join(self.decoders_supported )}' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[decoder_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = backbone_config SCREAMING_SNAKE_CASE_ = decoder_config # main feature dimension for the model SCREAMING_SNAKE_CASE_ = fpn_feature_size SCREAMING_SNAKE_CASE_ = mask_feature_size # initializer SCREAMING_SNAKE_CASE_ = init_std SCREAMING_SNAKE_CASE_ = init_xavier_std # Hungarian matcher && loss SCREAMING_SNAKE_CASE_ = cross_entropy_weight SCREAMING_SNAKE_CASE_ = dice_weight SCREAMING_SNAKE_CASE_ = mask_weight SCREAMING_SNAKE_CASE_ = use_auxiliary_loss SCREAMING_SNAKE_CASE_ = no_object_weight SCREAMING_SNAKE_CASE_ = output_auxiliary_logits SCREAMING_SNAKE_CASE_ = self.decoder_config.encoder_attention_heads SCREAMING_SNAKE_CASE_ = self.decoder_config.num_hidden_layers super().__init__(**SCREAMING_SNAKE_CASE_ ) @classmethod def _lowercase (cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return cls( backbone_config=SCREAMING_SNAKE_CASE_ , decoder_config=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ = self.decoder_config.to_dict() SCREAMING_SNAKE_CASE_ = self.__class__.model_type return output
628
0
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging lowerCAmelCase__ = logging.get_logger(__name__) class snake_case ( __lowercase ): UpperCAmelCase__ = ['''input_features'''] def __init__(self , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=1_60_00 , SCREAMING_SNAKE_CASE_=1_60 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=4_00 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__( feature_size=UpperCamelCase_ , sampling_rate=UpperCamelCase_ , padding_value=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , **UpperCamelCase_ , ) SCREAMING_SNAKE_CASE_ = n_fft SCREAMING_SNAKE_CASE_ = hop_length SCREAMING_SNAKE_CASE_ = chunk_length SCREAMING_SNAKE_CASE_ = chunk_length * sampling_rate SCREAMING_SNAKE_CASE_ = self.n_samples // hop_length SCREAMING_SNAKE_CASE_ = sampling_rate SCREAMING_SNAKE_CASE_ = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=UpperCamelCase_ , min_frequency=0.0 , max_frequency=80_00.0 , sampling_rate=UpperCamelCase_ , norm='''slaney''' , mel_scale='''slaney''' , ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = spectrogram( UpperCamelCase_ , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel='''log10''' , ) SCREAMING_SNAKE_CASE_ = log_spec[:, :-1] SCREAMING_SNAKE_CASE_ = np.maximum(UpperCamelCase_ , log_spec.max() - 8.0 ) SCREAMING_SNAKE_CASE_ = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def _lowercase (SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 0.0 ): """simple docstring""" if attention_mask is not None: SCREAMING_SNAKE_CASE_ = np.array(UpperCamelCase_ , np.intaa ) SCREAMING_SNAKE_CASE_ = [] for vector, length in zip(UpperCamelCase_ , attention_mask.sum(-1 ) ): SCREAMING_SNAKE_CASE_ = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: SCREAMING_SNAKE_CASE_ = padding_value normed_input_values.append(UpperCamelCase_ ) else: SCREAMING_SNAKE_CASE_ = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "max_length" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a' f' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input' f' was sampled with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) SCREAMING_SNAKE_CASE_ = isinstance(UpperCamelCase_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) SCREAMING_SNAKE_CASE_ = is_batched_numpy or ( isinstance(UpperCamelCase_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE_ = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(UpperCamelCase_ , np.ndarray ): SCREAMING_SNAKE_CASE_ = np.asarray(UpperCamelCase_ , dtype=np.floataa ) elif isinstance(UpperCamelCase_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE_ = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE_ = [np.asarray([raw_speech] ).T] SCREAMING_SNAKE_CASE_ = BatchFeature({'''input_features''': raw_speech} ) # convert into correct format for padding SCREAMING_SNAKE_CASE_ = self.pad( UpperCamelCase_ , padding=UpperCamelCase_ , max_length=max_length if max_length else self.n_samples , truncation=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: SCREAMING_SNAKE_CASE_ = self.zero_mean_unit_var_norm( padded_inputs['''input_features'''] , attention_mask=padded_inputs['''attention_mask'''] , padding_value=self.padding_value , ) SCREAMING_SNAKE_CASE_ = np.stack(padded_inputs['''input_features'''] , axis=0 ) # make sure list is in array format SCREAMING_SNAKE_CASE_ = padded_inputs.get('''input_features''' ).transpose(2 , 0 , 1 ) SCREAMING_SNAKE_CASE_ = [self._np_extract_fbank_features(UpperCamelCase_ ) for waveform in input_features[0]] if isinstance(input_features[0] , UpperCamelCase_ ): SCREAMING_SNAKE_CASE_ = [np.asarray(UpperCamelCase_ , dtype=np.floataa ) for feature in input_features] else: SCREAMING_SNAKE_CASE_ = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) SCREAMING_SNAKE_CASE_ = padded_inputs['attention_mask'][:, :: self.hop_length] if return_tensors is not None: SCREAMING_SNAKE_CASE_ = padded_inputs.convert_to_tensors(UpperCamelCase_ ) return padded_inputs def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
704
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] SCREAMING_SNAKE_CASE_ = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE_ = [4, 4, 4, 4] SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE_ = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE_ = 128 elif "large" in model_name: SCREAMING_SNAKE_CASE_ = 192 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE_ = 256 elif "huge" in model_name: SCREAMING_SNAKE_CASE_ = 352 # set label information SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE_ = '''imagenet-22k-id2label.json''' else: SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(__a, __a, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = FocalNetConfig( embed_dim=__a, depths=__a, focal_levels=__a, focal_windows=__a, use_conv_embed=__a, idalabel=__a, labelaid=__a, use_post_layernorm=__a, use_layerscale=__a, ) return config def _lowerCamelCase ( __a ): 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 "layers" in name: SCREAMING_SNAKE_CASE_ = '''encoder.''' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE_ = name.replace('''encoder.layers''', '''encoder.stages''' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('''downsample.proj''', '''downsample.projection''' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ = name.replace('''blocks''', '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.f''', '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.h''', '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.proj''', '''modulation.projection_out''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE_ = '''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE_ = '''layernorm.bias''' if "head" in name: SCREAMING_SNAKE_CASE_ = name.replace('''head''', '''classifier''' ) else: SCREAMING_SNAKE_CASE_ = '''focalnet.''' + name return name def _lowerCamelCase ( __a, __a, __a=False ): # fmt: off SCREAMING_SNAKE_CASE_ = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on SCREAMING_SNAKE_CASE_ = model_name_to_url[model_name] print('''Checkpoint URL: ''', __a ) SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(__a, map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = get_focalnet_config(__a ) SCREAMING_SNAKE_CASE_ = FocalNetForImageClassification(__a ) model.eval() # load state dict model.load_state_dict(__a ) # verify conversion SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = BitImageProcessor( do_resize=__a, size={'''shortest_edge''': 256}, resample=PILImageResampling.BILINEAR, do_center_crop=__a, crop_size=224, do_normalize=__a, image_mean=__a, image_std=__a, ) SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__a, stream=__a ).raw ) SCREAMING_SNAKE_CASE_ = processor(images=__a, return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE_ = image_transforms(__a ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values, __a, atol=1E-4 ) SCREAMING_SNAKE_CASE_ = model(**__a ) SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(-1 ).item() print('''Predicted class:''', model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''', outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE_ = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE_ = torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8] ) assert torch.allclose(outputs.logits[0, :3], __a, atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model and processor of {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if push_to_hub: print(F'Pushing model and processor of {model_name} to the hub...' ) model.push_to_hub(F'{model_name}' ) processor.push_to_hub(F'{model_name}' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
628
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCAmelCase__ = { "configuration_gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig", "GPTNeoOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ "GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoForCausalLM", "GPTNeoForQuestionAnswering", "GPTNeoForSequenceClassification", "GPTNeoForTokenClassification", "GPTNeoModel", "GPTNeoPreTrainedModel", "load_tf_weights_in_gpt_neo", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ "FlaxGPTNeoForCausalLM", "FlaxGPTNeoModel", "FlaxGPTNeoPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class snake_case ( __lowercase ): UpperCAmelCase__ = '''glpn''' def __init__(self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[8, 4, 2, 1] , SCREAMING_SNAKE_CASE_=[32, 64, 1_60, 2_56] , SCREAMING_SNAKE_CASE_=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE_=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[1, 2, 5, 8] , SCREAMING_SNAKE_CASE_=[4, 4, 4, 4] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1e-6 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=-1 , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) 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_ = initializer_range SCREAMING_SNAKE_CASE_ = drop_path_rate SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = decoder_hidden_size SCREAMING_SNAKE_CASE_ = max_depth SCREAMING_SNAKE_CASE_ = head_in_index
628
0
"""simple docstring""" import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class snake_case ( __lowerCamelCase ): def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = data def __iter__(self ): """simple docstring""" for element in self.data: yield element def _lowerCamelCase ( __a=True ): SCREAMING_SNAKE_CASE_ = Accelerator(even_batches=lowerCamelCase_ ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _lowerCamelCase ( __a, __a, __a, __a = False ): if iterable: SCREAMING_SNAKE_CASE_ = DummyIterableDataset(torch.as_tensor(range(lowerCamelCase_ ) ) ) else: SCREAMING_SNAKE_CASE_ = TensorDataset(torch.as_tensor(range(lowerCamelCase_ ) ) ) SCREAMING_SNAKE_CASE_ = DataLoader(lowerCamelCase_, batch_size=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(lowerCamelCase_ ) return dl def _lowerCamelCase ( __a, __a, __a, __a, __a, ): SCREAMING_SNAKE_CASE_ = create_dataloader(accelerator=lowerCamelCase_, dataset_size=lowerCamelCase_, batch_size=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( lowerCamelCase_, dataset_size=3, batch_size=1, process_0_expected_batch_sizes=[1, 1], process_1_expected_batch_sizes=[1, 1], ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( lowerCamelCase_, dataset_size=7, batch_size=2, process_0_expected_batch_sizes=[2, 2], process_1_expected_batch_sizes=[2, 2], ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = create_accelerator(even_batches=lowerCamelCase_ ) verify_dataloader_batch_sizes( lowerCamelCase_, dataset_size=3, batch_size=1, process_0_expected_batch_sizes=[1, 1], process_1_expected_batch_sizes=[1], ) verify_dataloader_batch_sizes( lowerCamelCase_, dataset_size=7, batch_size=2, process_0_expected_batch_sizes=[2, 2], process_1_expected_batch_sizes=[2, 1], ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = create_accelerator(even_batches=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = torch.nn.Linear(1, 1 ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = create_dataloader(lowerCamelCase_, dataset_size=3, batch_size=1 ) SCREAMING_SNAKE_CASE_ = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(lowerCamelCase_ ): SCREAMING_SNAKE_CASE_ = ddp_model(batch[0].float() ) SCREAMING_SNAKE_CASE_ = output.sum() loss.backward() batch_idxs.append(lowerCamelCase_ ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _lowerCamelCase ( __a ): with warnings.catch_warnings(record=lowerCamelCase_ ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category, lowerCamelCase_ ) assert "only supported for multi-GPU" in str(w[-1].message ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = create_accelerator(even_batches=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = torch.nn.Linear(1, 1 ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = create_dataloader(lowerCamelCase_, dataset_size=3, batch_size=1 ) SCREAMING_SNAKE_CASE_ = create_dataloader(lowerCamelCase_, dataset_size=3, batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model], even_batches=lowerCamelCase_ ): SCREAMING_SNAKE_CASE_ = train_dl.batch_sampler.even_batches SCREAMING_SNAKE_CASE_ = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = create_accelerator(even_batches=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = torch.nn.Linear(1, 1 ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(lowerCamelCase_ ) create_dataloader(lowerCamelCase_, dataset_size=3, batch_size=1, iterable=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = create_dataloader(lowerCamelCase_, dataset_size=3, batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('''ignore''' ) try: with accelerator.join_uneven_inputs([ddp_model], even_batches=lowerCamelCase_ ): SCREAMING_SNAKE_CASE_ = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = create_accelerator() SCREAMING_SNAKE_CASE_ = torch.nn.Linear(1, 1 ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(lowerCamelCase_ ) create_dataloader(lowerCamelCase_, dataset_size=3, batch_size=1, iterable=lowerCamelCase_ ) with warnings.catch_warnings(record=lowerCamelCase_ ) as w: with accelerator.join_uneven_inputs([ddp_model], even_batches=lowerCamelCase_ ): pass assert issubclass(w[-1].category, lowerCamelCase_ ) assert "only supported for map-style datasets" in str(w[-1].message ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = create_accelerator() accelerator.print('''Test that even_batches variable ensures uniform batches across processes''' ) test_default_ensures_even_batch_sizes() accelerator.print('''Run tests with even_batches disabled''' ) test_can_disable_even_batches() accelerator.print('''Test joining uneven inputs''' ) test_can_join_uneven_inputs() accelerator.print('''Test overriding even_batches when joining uneven inputs''' ) test_join_can_override_even_batches() accelerator.print('''Test overriding even_batches for mixed dataloader types''' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('''Test overriding even_batches raises a warning for iterable dataloaders''' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('''Test join with non DDP distributed raises warning''' ) SCREAMING_SNAKE_CASE_ = accelerator.state.distributed_type SCREAMING_SNAKE_CASE_ = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = original_state if __name__ == "__main__": main()
706
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = KandinskyVaaControlnetPipeline UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCAmelCase__ = False @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return self.time_input_dim @property def _lowercase (self ): """simple docstring""" return self.time_input_dim * 4 @property def _lowercase (self ): """simple docstring""" return 1_00 @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE_ = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def _lowercase (self ): """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = VQModel(**self.dummy_movq_kwargs ) return model def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.dummy_unet SCREAMING_SNAKE_CASE_ = self.dummy_movq SCREAMING_SNAKE_CASE_ = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='''linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , steps_offset=1 , prediction_type='''epsilon''' , thresholding=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): """simple docstring""" SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( SCREAMING_SNAKE_CASE_ ) # create hint SCREAMING_SNAKE_CASE_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = { '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 64, '''width''': 64, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''cpu''' SCREAMING_SNAKE_CASE_ = self.get_dummy_components() SCREAMING_SNAKE_CASE_ = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = output.images SCREAMING_SNAKE_CASE_ = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[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.6_95_98_26, 0.86_82_79, 0.7_55_80_92, 0.68_76_94_67, 0.85_80_58_04, 0.65_97_74_96, 0.44_88_53_02, 0.5_95_91_11, 0.4_25_15_95] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy''' ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE_ ) ).float() / 2_55.0 SCREAMING_SNAKE_CASE_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) SCREAMING_SNAKE_CASE_ = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = KandinskyVaaControlnetPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''A robot, 4k photo''' SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = pipe_prior( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipeline( image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , hint=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=1_00 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
628
0
import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } lowerCAmelCase__ = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } lowerCAmelCase__ = {"facebook/blenderbot_small-90M": 512} def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = set() SCREAMING_SNAKE_CASE_ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE_ = char SCREAMING_SNAKE_CASE_ = set(__a ) return pairs class snake_case ( UpperCAmelCase_ ): UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = ['input_ids', 'attention_mask'] def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="__start__" , SCREAMING_SNAKE_CASE_="__end__" , SCREAMING_SNAKE_CASE_="__unk__" , SCREAMING_SNAKE_CASE_="__null__" , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(unk_token=_lowercase , bos_token=_lowercase , eos_token=_lowercase , pad_token=_lowercase , **_lowercase ) with open(_lowercase , encoding='''utf-8''' ) as vocab_handle: SCREAMING_SNAKE_CASE_ = json.load(_lowercase ) SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()} with open(_lowercase , encoding='''utf-8''' ) as merges_handle: SCREAMING_SNAKE_CASE_ = merges_handle.read().split('''\n''' )[1:-1] SCREAMING_SNAKE_CASE_ = [tuple(merge.split() ) for merge in merges] SCREAMING_SNAKE_CASE_ = dict(zip(_lowercase , range(len(_lowercase ) ) ) ) SCREAMING_SNAKE_CASE_ = {} @property def _lowercase (self ): """simple docstring""" return len(self.encoder ) def _lowercase (self ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE_ = re.sub('''([.,!?()])''' , R''' \1''' , _lowercase ) SCREAMING_SNAKE_CASE_ = re.sub('''(\')''' , R''' \1 ''' , _lowercase ) SCREAMING_SNAKE_CASE_ = re.sub(R'''\s{2,}''' , ''' ''' , _lowercase ) if "\n" in token: SCREAMING_SNAKE_CASE_ = token.replace('''\n''' , ''' __newln__''' ) SCREAMING_SNAKE_CASE_ = token.split(''' ''' ) SCREAMING_SNAKE_CASE_ = [] for token in tokens: if not len(_lowercase ): continue SCREAMING_SNAKE_CASE_ = token.lower() SCREAMING_SNAKE_CASE_ = tuple(_lowercase ) SCREAMING_SNAKE_CASE_ = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) SCREAMING_SNAKE_CASE_ = get_pairs(_lowercase ) if not pairs: words.append(_lowercase ) continue while True: SCREAMING_SNAKE_CASE_ = min(_lowercase , key=lambda SCREAMING_SNAKE_CASE_ : self.bpe_ranks.get(_lowercase , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE_ = bigram SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 0 while i < len(_lowercase ): try: SCREAMING_SNAKE_CASE_ = word.index(_lowercase , _lowercase ) new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE_ = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(_lowercase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE_ = tuple(_lowercase ) SCREAMING_SNAKE_CASE_ = new_word if len(_lowercase ) == 1: break else: SCREAMING_SNAKE_CASE_ = get_pairs(_lowercase ) SCREAMING_SNAKE_CASE_ = '@@ '.join(_lowercase ) SCREAMING_SNAKE_CASE_ = word[:-4] SCREAMING_SNAKE_CASE_ = word words.append(_lowercase ) return " ".join(_lowercase ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = re.findall(R'''\S+\n?''' , _lowercase ) for token in words: split_tokens.extend(list(self.bpe(_lowercase ).split(''' ''' ) ) ) return split_tokens def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = token.lower() return self.encoder.get(_lowercase , self.encoder.get(self.unk_token ) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.decoder.get(_lowercase , self.unk_token ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ' '.join(_lowercase ).replace('''@@ ''' , '''''' ).strip() return out_string def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): """simple docstring""" if not os.path.isdir(_lowercase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return SCREAMING_SNAKE_CASE_ = os.path.join( _lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE_ = os.path.join( _lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(_lowercase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_lowercase , ensure_ascii=_lowercase ) + '''\n''' ) SCREAMING_SNAKE_CASE_ = 0 with open(_lowercase , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ''' Please check that the tokenizer is not corrupted!''' ) SCREAMING_SNAKE_CASE_ = token_index writer.write(''' '''.join(_lowercase ) + '''\n''' ) index += 1 return vocab_file, merge_file
707
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class snake_case ( __lowercase ): UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_="cls" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = project_dim SCREAMING_SNAKE_CASE_ = pooler_fn SCREAMING_SNAKE_CASE_ = learn_encoder SCREAMING_SNAKE_CASE_ = use_attention_mask class snake_case ( __lowercase ): UpperCAmelCase__ = [R'''pooler''', R'''logit_scale'''] UpperCAmelCase__ = [R'''position_ids''', R'''predictions.decoder.bias'''] UpperCAmelCase__ = '''roberta''' UpperCAmelCase__ = RobertaSeriesConfig def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = XLMRobertaModel(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = getattr(SCREAMING_SNAKE_CASE_ , '''has_pre_transformation''' , SCREAMING_SNAKE_CASE_ ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def _lowercase (self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE_ = self.base_model( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , position_ids=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=SCREAMING_SNAKE_CASE_ , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = outputs['''hidden_states'''][-2] SCREAMING_SNAKE_CASE_ = self.pre_LN(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.transformation_pre(SCREAMING_SNAKE_CASE_ ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE_ = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
628
0
"""simple docstring""" from math import sqrt def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and ( number >= 0 ), "'number' must been an int and positive" SCREAMING_SNAKE_CASE_ = True # 0 and 1 are none primes. if number <= 1: SCREAMING_SNAKE_CASE_ = False for divisor in range(2, int(round(sqrt(__A ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: SCREAMING_SNAKE_CASE_ = False break # precondition assert isinstance(__A, __A ), "'status' must been from type bool" return status def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N SCREAMING_SNAKE_CASE_ = list(range(2, n + 1 ) ) SCREAMING_SNAKE_CASE_ = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(__A ) ): for j in range(i + 1, len(__A ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): SCREAMING_SNAKE_CASE_ = 0 # filters actual prime numbers. SCREAMING_SNAKE_CASE_ = [x for x in begin_list if x != 0] # precondition assert isinstance(__A, __A ), "'ans' must been from type list" return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and (n > 2), "'N' must been an int and > 2" SCREAMING_SNAKE_CASE_ = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1 ): if is_prime(__A ): ans.append(__A ) # precondition assert isinstance(__A, __A ), "'ans' must been from type list" return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and number >= 0, "'number' must been an int and >= 0" SCREAMING_SNAKE_CASE_ = [] # this list will be returns of the function. # potential prime number factors. SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = number if number == 0 or number == 1: ans.append(__A ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(__A ): while quotient != 1: if is_prime(__A ) and (quotient % factor == 0): ans.append(__A ) quotient /= factor else: factor += 1 else: ans.append(__A ) # precondition assert isinstance(__A, __A ), "'ans' must been from type list" return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and ( number >= 0 ), "'number' bust been an int and >= 0" SCREAMING_SNAKE_CASE_ = 0 # prime factorization of 'number' SCREAMING_SNAKE_CASE_ = prime_factorization(__A ) SCREAMING_SNAKE_CASE_ = max(__A ) # precondition assert isinstance(__A, __A ), "'ans' must been from type int" return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and ( number >= 0 ), "'number' bust been an int and >= 0" SCREAMING_SNAKE_CASE_ = 0 # prime factorization of 'number' SCREAMING_SNAKE_CASE_ = prime_factorization(__A ) SCREAMING_SNAKE_CASE_ = min(__A ) # precondition assert isinstance(__A, __A ), "'ans' must been from type int" return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ), "'number' must been an int" assert isinstance(number % 2 == 0, __A ), "compare bust been from type bool" return number % 2 == 0 def _lowerCamelCase ( __a ): assert isinstance(__A, __A ), "'number' must been an int" assert isinstance(number % 2 != 0, __A ), "compare bust been from type bool" return number % 2 != 0 def _lowerCamelCase ( __a ): assert ( isinstance(__A, __A ) and (number > 2) and is_even(__A ) ), "'number' must been an int, even and > 2" SCREAMING_SNAKE_CASE_ = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' SCREAMING_SNAKE_CASE_ = get_prime_numbers(__A ) SCREAMING_SNAKE_CASE_ = len(__A ) # run variable for while-loops. SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = None # exit variable. for break up the loops SCREAMING_SNAKE_CASE_ = True while i < len_pn and loop: SCREAMING_SNAKE_CASE_ = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: SCREAMING_SNAKE_CASE_ = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(__A, __A ) and (len(__A ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def _lowerCamelCase ( __a, __a ): assert ( isinstance(__A, __A ) and isinstance(__A, __A ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." SCREAMING_SNAKE_CASE_ = 0 while numbera != 0: SCREAMING_SNAKE_CASE_ = numbera % numbera SCREAMING_SNAKE_CASE_ = numbera SCREAMING_SNAKE_CASE_ = rest # precondition assert isinstance(__A, __A ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def _lowerCamelCase ( __a, __a ): assert ( isinstance(__A, __A ) and isinstance(__A, __A ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." SCREAMING_SNAKE_CASE_ = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' SCREAMING_SNAKE_CASE_ = prime_factorization(__A ) SCREAMING_SNAKE_CASE_ = prime_factorization(__A ) elif numbera == 1 or numbera == 1: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = max(__A, __A ) SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__A ) SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__A ) for _ in range(max(__A, __A ) ): ans *= n else: SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__A ) for _ in range(__A ): ans *= n done.append(__A ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__A ) for _ in range(__A ): ans *= n done.append(__A ) # precondition assert isinstance(__A, __A ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and (n >= 0), "'number' must been a positive int" SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(__A ): ans += 1 # precondition assert isinstance(__A, __A ) and is_prime( __A ), "'ans' must been a prime number and from type int" return ans def _lowerCamelCase ( __a, __a ): assert ( is_prime(__A ) and is_prime(__A ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" SCREAMING_SNAKE_CASE_ = p_number_a + 1 # jump to the next number SCREAMING_SNAKE_CASE_ = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(__A ): number += 1 while number < p_number_a: ans.append(__A ) number += 1 # fetch the next prime number. while not is_prime(__A ): number += 1 # precondition assert ( isinstance(__A, __A ) and ans[0] != p_number_a and ans[len(__A ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and (n >= 1), "'n' must been int and >= 1" SCREAMING_SNAKE_CASE_ = [] # will be returned. for divisor in range(1, n + 1 ): if n % divisor == 0: ans.append(__A ) # precondition assert ans[0] == 1 and ans[len(__A ) - 1] == n, "Error in function getDivisiors(...)" return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and ( number > 1 ), "'number' must been an int and >= 1" SCREAMING_SNAKE_CASE_ = get_divisors(__A ) # precondition assert ( isinstance(__A, __A ) and (divisors[0] == 1) and (divisors[len(__A ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def _lowerCamelCase ( __a, __a ): assert ( isinstance(__A, __A ) and isinstance(__A, __A ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. SCREAMING_SNAKE_CASE_ = gcd(abs(__A ), abs(__A ) ) # precondition assert ( isinstance(__A, __A ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and (n >= 0), "'n' must been a int and >= 0" SCREAMING_SNAKE_CASE_ = 1 # this will be return. for factor in range(1, n + 1 ): ans *= factor return ans def _lowerCamelCase ( __a ): assert isinstance(__A, __A ) and (n >= 0), "'n' must been an int and >= 0" SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 1 # this will be return for _ in range(n - 1 ): SCREAMING_SNAKE_CASE_ = ans ans += fiba SCREAMING_SNAKE_CASE_ = tmp return ans
708
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _lowerCamelCase ( __a, __a=0.9_9_9, __a="cosine", ): if alpha_transform_type == "cosine": def alpha_bar_fn(__a ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__a ): return math.exp(t * -1_2.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) SCREAMING_SNAKE_CASE_ = [] for i in range(__a ): SCREAMING_SNAKE_CASE_ = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__a ) / alpha_bar_fn(__a ), __a ) ) return torch.tensor(__a, dtype=torch.floataa ) class snake_case ( __lowercase , __lowercase ): UpperCAmelCase__ = [e.name for e in KarrasDiffusionSchedulers] UpperCAmelCase__ = 2 @register_to_config def __init__(self , SCREAMING_SNAKE_CASE_ = 10_00 , SCREAMING_SNAKE_CASE_ = 0.0_00_85 , SCREAMING_SNAKE_CASE_ = 0.0_12 , SCREAMING_SNAKE_CASE_ = "linear" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "epsilon" , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = "linspace" , SCREAMING_SNAKE_CASE_ = 0 , ): """simple docstring""" if trained_betas is not None: SCREAMING_SNAKE_CASE_ = torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE_ = torch.linspace(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) SCREAMING_SNAKE_CASE_ = 1.0 - self.betas SCREAMING_SNAKE_CASE_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = use_karras_sigmas def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" if schedule_timesteps is None: SCREAMING_SNAKE_CASE_ = self.timesteps SCREAMING_SNAKE_CASE_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: SCREAMING_SNAKE_CASE_ = 1 if len(SCREAMING_SNAKE_CASE_ ) > 1 else 0 else: SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep SCREAMING_SNAKE_CASE_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self ): """simple docstring""" if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = num_inference_steps SCREAMING_SNAKE_CASE_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": SCREAMING_SNAKE_CASE_ = np.linspace(0 , num_train_timesteps - 1 , SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )[::-1].copy() elif self.config.timestep_spacing == "leading": SCREAMING_SNAKE_CASE_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(0 , SCREAMING_SNAKE_CASE_ ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": SCREAMING_SNAKE_CASE_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(SCREAMING_SNAKE_CASE_ , 0 , -step_ratio )).round().copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps -= 1 else: raise ValueError( f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) SCREAMING_SNAKE_CASE_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.interp(SCREAMING_SNAKE_CASE_ , np.arange(0 , len(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) if self.config.use_karras_sigmas: SCREAMING_SNAKE_CASE_ = self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE_ , num_inference_steps=self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for sigma in sigmas] ) SCREAMING_SNAKE_CASE_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = timesteps.to(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = timesteps.to(device=SCREAMING_SNAKE_CASE_ ) # empty dt and derivative SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter SCREAMING_SNAKE_CASE_ = defaultdict(SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) # get distribution SCREAMING_SNAKE_CASE_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range SCREAMING_SNAKE_CASE_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) SCREAMING_SNAKE_CASE_ = low_idx + 1 SCREAMING_SNAKE_CASE_ = log_sigmas[low_idx] SCREAMING_SNAKE_CASE_ = log_sigmas[high_idx] # interpolate sigmas SCREAMING_SNAKE_CASE_ = (low - log_sigma) / (low - high) SCREAMING_SNAKE_CASE_ = np.clip(SCREAMING_SNAKE_CASE_ , 0 , 1 ) # transform interpolation to time range SCREAMING_SNAKE_CASE_ = (1 - w) * low_idx + w * high_idx SCREAMING_SNAKE_CASE_ = t.reshape(sigma.shape ) return t def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = in_sigmas[-1].item() SCREAMING_SNAKE_CASE_ = in_sigmas[0].item() SCREAMING_SNAKE_CASE_ = 7.0 # 7.0 is the value used in the paper SCREAMING_SNAKE_CASE_ = np.linspace(0 , 1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = sigma_min ** (1 / rho) SCREAMING_SNAKE_CASE_ = sigma_max ** (1 / rho) SCREAMING_SNAKE_CASE_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self ): """simple docstring""" return self.dt is None def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) # advance index counter by 1 SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = self.sigmas[step_index - 1] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE_ = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: SCREAMING_SNAKE_CASE_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep SCREAMING_SNAKE_CASE_ = sigma_next - sigma_hat # store for 2nd order step SCREAMING_SNAKE_CASE_ = derivative SCREAMING_SNAKE_CASE_ = dt SCREAMING_SNAKE_CASE_ = sample else: # 2. 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_next SCREAMING_SNAKE_CASE_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample SCREAMING_SNAKE_CASE_ = self.dt SCREAMING_SNAKE_CASE_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE_ ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = [self.index_for_timestep(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for t in timesteps] SCREAMING_SNAKE_CASE_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): SCREAMING_SNAKE_CASE_ = sigma.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_ = original_samples + noise * sigma return noisy_samples def __len__(self ): """simple docstring""" return self.config.num_train_timesteps
628
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
709
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = 8 # DPR tok SCREAMING_SNAKE_CASE_ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , DPR_VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) # BART tok SCREAMING_SNAKE_CASE_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE_ = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''bart_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self ): """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''bart_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''custom''' , ) if from_disk: SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dataset''' ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''index.faiss''' ) dataset.get_index('''embeddings''' ).save(os.path.join(self.tmpdirname , '''index.faiss''' ) ) dataset.drop_index('''embeddings''' ) dataset.save_to_disk(os.path.join(self.tmpdirname , '''dataset''' ) ) del dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , SCREAMING_SNAKE_CASE_ ) , ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''hf_bert_base.hnswSQ8_correct_phi_128.c_index''' ) dataset.save_faiss_index('''embeddings''' , index_file_name + '''.index.dpr''' ) pickle.dump(dataset['''id'''] , open(index_file_name + '''.index_meta.dpr''' , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''psgs_w100.tsv.pkl''' ) SCREAMING_SNAKE_CASE_ = {sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset} pickle.dump(SCREAMING_SNAKE_CASE_ , open(SCREAMING_SNAKE_CASE_ , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''legacy''' , index_path=self.tmpdirname , ) SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''text'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''text'''][0] , '''bar''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''text'''][0] , '''foo''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) SCREAMING_SNAKE_CASE_ = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( # noqa: F841 out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], out['''doc_ids'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dpr_ctx_encoder_tokenizer() SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) retriever.set_ctx_encoder_tokenizer(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual( len(SCREAMING_SNAKE_CASE_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''') ) , SCREAMING_SNAKE_CASE_ ) # check for doc token related keys in dictionary.
628
0
"""simple docstring""" import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class snake_case ( __lowercase , __lowercase , __lowercase , unittest.TestCase ): UpperCAmelCase__ = StableUnCLIPPipeline UpperCAmelCase__ = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__ = TEXT_TO_IMAGE_BATCH_PARAMS UpperCAmelCase__ = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase__ = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 32 SCREAMING_SNAKE_CASE_ = embedder_hidden_size # prior components torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=UpperCamelCase_ , projection_dim=UpperCamelCase_ , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=UpperCamelCase_ , num_layers=1 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=10_00 , clip_sample=UpperCamelCase_ , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = StableUnCLIPImageNormalizer(embedding_dim=UpperCamelCase_ ) SCREAMING_SNAKE_CASE_ = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=UpperCamelCase_ , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=UpperCamelCase_ , layers_per_block=1 , upcast_attention=UpperCamelCase_ , use_linear_projection=UpperCamelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type='''v_prediction''' , set_alpha_to_one=UpperCamelCase_ , steps_offset=1 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = AutoencoderKL() SCREAMING_SNAKE_CASE_ = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): """simple docstring""" if str(UpperCamelCase_ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE_ = torch.manual_seed(UpperCamelCase_ ) else: SCREAMING_SNAKE_CASE_ = torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ ) SCREAMING_SNAKE_CASE_ = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=UpperCamelCase_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=UpperCamelCase_ ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) SCREAMING_SNAKE_CASE_ = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe('''anime turle''' , generator=UpperCamelCase_ , output_type='''np''' ) SCREAMING_SNAKE_CASE_ = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(UpperCamelCase_ , UpperCamelCase_ ) def _lowercase (self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE_ = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE_ = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
710
"""simple docstring""" from collections.abc import Sequence from queue import Queue class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = start SCREAMING_SNAKE_CASE_ = end SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = left SCREAMING_SNAKE_CASE_ = right def __repr__(self ): """simple docstring""" return f'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = collection SCREAMING_SNAKE_CASE_ = function if self.collection: SCREAMING_SNAKE_CASE_ = self._build_tree(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self._update_tree(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self._query_range(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.collection[start] ) SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = self._build_tree(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE_ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == i: SCREAMING_SNAKE_CASE_ = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.fn(node.left.val , node.right.val ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE_ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE_ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" if self.root is not None: SCREAMING_SNAKE_CASE_ = Queue() queue.put(self.root ) while not queue.empty(): SCREAMING_SNAKE_CASE_ = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('*' * 50) lowerCAmelCase__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
628
0
"""simple docstring""" from importlib import import_module from .logging import get_logger lowerCAmelCase__ = get_logger(__name__) class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('''__''' ): setattr(self , __A , getattr(__A , __A ) ) SCREAMING_SNAKE_CASE_ = module._original_module if isinstance(__A , _PatchedModuleObj ) else module class snake_case : UpperCAmelCase__ = [] def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = obj SCREAMING_SNAKE_CASE_ = target SCREAMING_SNAKE_CASE_ = new SCREAMING_SNAKE_CASE_ = target.split('''.''' )[0] SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = attrs or [] def __enter__(self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.target.split('''.''' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__A ) ): try: SCREAMING_SNAKE_CASE_ = import_module('''.'''.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): SCREAMING_SNAKE_CASE_ = getattr(self.obj , __A ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__A , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): SCREAMING_SNAKE_CASE_ = obj_attr # patch at top level setattr(self.obj , __A , _PatchedModuleObj(__A , attrs=self.attrs ) ) SCREAMING_SNAKE_CASE_ = getattr(self.obj , __A ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__A , __A , _PatchedModuleObj(getattr(__A , __A , __A ) , attrs=self.attrs ) ) SCREAMING_SNAKE_CASE_ = getattr(__A , __A ) # finally set the target attribute setattr(__A , __A , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: SCREAMING_SNAKE_CASE_ = getattr(import_module('''.'''.join(__A ) ) , __A ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __A ) is attr_value: SCREAMING_SNAKE_CASE_ = getattr(self.obj , __A ) setattr(self.obj , __A , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" SCREAMING_SNAKE_CASE_ = globals()["__builtins__"][target_attr] setattr(self.obj , __A , self.new ) else: raise RuntimeError(f'Tried to patch attribute {target_attr} instead of a submodule.' ) def __exit__(self , *SCREAMING_SNAKE_CASE_ ): """simple docstring""" for attr in list(self.original ): setattr(self.obj , __A , self.original.pop(__A ) ) def _lowercase (self ): """simple docstring""" self.__enter__() self._active_patches.append(self ) def _lowercase (self ): """simple docstring""" try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
711
"""simple docstring""" def _lowerCamelCase ( __a ): if not isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be an integer' raise TypeError(__a ) if number < 1: SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be > 0' raise ValueError(__a ) SCREAMING_SNAKE_CASE_ = 1 for i in range(1, __a ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
628
0
"""simple docstring""" import numpy as np class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" self.set_matricies(red=_a , green=_a , blue=_a , red_edge=_a , nir=_a ) def _lowercase (self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" if red is not None: SCREAMING_SNAKE_CASE_ = red if green is not None: SCREAMING_SNAKE_CASE_ = green if blue is not None: SCREAMING_SNAKE_CASE_ = blue if red_edge is not None: SCREAMING_SNAKE_CASE_ = red_edge if nir is not None: SCREAMING_SNAKE_CASE_ = nir return True def _lowercase (self , SCREAMING_SNAKE_CASE_="" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" self.set_matricies(red=_a , green=_a , blue=_a , red_edge=_a , nir=_a ) SCREAMING_SNAKE_CASE_ = { """ARVI2""": self.arvaa, """CCCI""": self.ccci, """CVI""": self.cvi, """GLI""": self.gli, """NDVI""": self.ndvi, """BNDVI""": self.bndvi, """redEdgeNDVI""": self.red_edge_ndvi, """GNDVI""": self.gndvi, """GBNDVI""": self.gbndvi, """GRNDVI""": self.grndvi, """RBNDVI""": self.rbndvi, """PNDVI""": self.pndvi, """ATSAVI""": self.atsavi, """BWDRVI""": self.bwdrvi, """CIgreen""": self.ci_green, """CIrededge""": self.ci_rededge, """CI""": self.ci, """CTVI""": self.ctvi, """GDVI""": self.gdvi, """EVI""": self.evi, """GEMI""": self.gemi, """GOSAVI""": self.gosavi, """GSAVI""": self.gsavi, """Hue""": self.hue, """IVI""": self.ivi, """IPVI""": self.ipvi, """I""": self.i, """RVI""": self.rvi, """MRVI""": self.mrvi, """MSAVI""": self.m_savi, """NormG""": self.norm_g, """NormNIR""": self.norm_nir, """NormR""": self.norm_r, """NGRDI""": self.ngrdi, """RI""": self.ri, """S""": self.s, """IF""": self._if, """DVI""": self.dvi, """TVI""": self.tvi, """NDRE""": self.ndre, } try: return funcs[index]() except KeyError: print('''Index not in the list!''' ) return False def _lowercase (self ): """simple docstring""" return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def _lowercase (self ): """simple docstring""" return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def _lowercase (self ): """simple docstring""" return self.nir * (self.red / (self.green**2)) def _lowercase (self ): """simple docstring""" return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def _lowercase (self ): """simple docstring""" return (self.nir - self.red) / (self.nir + self.red) def _lowercase (self ): """simple docstring""" return (self.nir - self.blue) / (self.nir + self.blue) def _lowercase (self ): """simple docstring""" return (self.redEdge - self.red) / (self.redEdge + self.red) def _lowercase (self ): """simple docstring""" return (self.nir - self.green) / (self.nir + self.green) def _lowercase (self ): """simple docstring""" return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def _lowercase (self ): """simple docstring""" return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def _lowercase (self ): """simple docstring""" return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def _lowercase (self ): """simple docstring""" return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def _lowercase (self , SCREAMING_SNAKE_CASE_=0.08 , SCREAMING_SNAKE_CASE_=1.22 , SCREAMING_SNAKE_CASE_=0.03 ): """simple docstring""" return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def _lowercase (self ): """simple docstring""" return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def _lowercase (self ): """simple docstring""" return (self.nir / self.green) - 1 def _lowercase (self ): """simple docstring""" return (self.nir / self.redEdge) - 1 def _lowercase (self ): """simple docstring""" return (self.red - self.blue) / self.red def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def _lowercase (self ): """simple docstring""" return self.nir - self.green def _lowercase (self ): """simple docstring""" return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.1_25) / (1 - self.red) def _lowercase (self , SCREAMING_SNAKE_CASE_=0.16 ): """simple docstring""" return (self.nir - self.green) / (self.nir + self.green + y) def _lowercase (self , SCREAMING_SNAKE_CASE_=0.5 ): """simple docstring""" return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def _lowercase (self ): """simple docstring""" return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def _lowercase (self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" return (self.nir - b) / (a * self.red) def _lowercase (self ): """simple docstring""" return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def _lowercase (self ): """simple docstring""" return (self.red + self.green + self.blue) / 30.5 def _lowercase (self ): """simple docstring""" return self.nir / self.red def _lowercase (self ): """simple docstring""" return (self.rvi() - 1) / (self.rvi() + 1) def _lowercase (self ): """simple docstring""" return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def _lowercase (self ): """simple docstring""" return self.green / (self.nir + self.red + self.green) def _lowercase (self ): """simple docstring""" return self.nir / (self.nir + self.red + self.green) def _lowercase (self ): """simple docstring""" return self.red / (self.nir + self.red + self.green) def _lowercase (self ): """simple docstring""" return (self.green - self.red) / (self.green + self.red) def _lowercase (self ): """simple docstring""" return (self.red - self.green) / (self.red + self.green) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) SCREAMING_SNAKE_CASE_ = np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def _lowercase (self ): """simple docstring""" return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def _lowercase (self ): """simple docstring""" return self.nir / self.red def _lowercase (self ): """simple docstring""" return (self.ndvi() + 0.5) ** (1 / 2) def _lowercase (self ): """simple docstring""" return (self.nir - self.redEdge) / (self.nir + self.redEdge)
712
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = len(__a ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: SCREAMING_SNAKE_CASE_ = i + 1 else: SCREAMING_SNAKE_CASE_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f'''{two_pointer([2, 7, 11, 15], 9) = }''')
628
0
"""simple docstring""" def _lowerCamelCase ( __a = 100 ): SCREAMING_SNAKE_CASE_ = n * (n + 1) * (2 * n + 1) / 6 SCREAMING_SNAKE_CASE_ = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f'''{solution() = }''')
713
"""simple docstring""" import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a=2, __a=3, __a=16, __a = 10, __a = 2 ): def get_dataset(__a ): SCREAMING_SNAKE_CASE_ = torch.randn(batch_size * n_batches, 1 ) return TensorDataset(__a, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1 ) ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) return (train_dataloader, valid_dataloader) def _lowerCamelCase ( __a, __a, __a, __a, __a, __a=None ): SCREAMING_SNAKE_CASE_ = [] for epoch in range(__a ): # Train quickly model.train() for batch in dataloader: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = batch SCREAMING_SNAKE_CASE_ = model(__a ) SCREAMING_SNAKE_CASE_ = torch.nn.functional.mse_loss(__a, __a ) accelerator.backward(__a ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class snake_case ( nn.Module ): def __init__(self ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return x * self.a + self.b class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(total_limit=1 , project_dir=SCREAMING_SNAKE_CASE_ , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''initial''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoint''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) # Load everything back in and make sure all states work accelerator.load_state(SCREAMING_SNAKE_CASE_ ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_1''' ) ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch.tensor([1, 2, 3] ) SCREAMING_SNAKE_CASE_ = torch.tensor([2, 3, 4] ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(net.parameters() ) SCREAMING_SNAKE_CASE_ = Accelerator() with self.assertRaises(SCREAMING_SNAKE_CASE_ ) as ve: accelerator.register_for_checkpointing(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = str(ve.exception ) self.assertTrue('''Item at index 0''' in message ) self.assertTrue('''Item at index 1''' in message ) self.assertFalse('''Item at index 2''' in message ) self.assertFalse('''Item at index 3''' in message ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ = torch.optim.lr_scheduler.StepLR(SCREAMING_SNAKE_CASE_ , step_size=1 , gamma=0.99 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() SCREAMING_SNAKE_CASE_ = scheduler.state_dict() train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) self.assertEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ , total_limit=2 ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_9''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_10''' ) ) ) @require_cuda def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() ) if __name__ == "__main__": lowerCAmelCase__ = '/tmp/accelerate/state_checkpointing' lowerCAmelCase__ = DummyModel() lowerCAmelCase__ = torch.optim.Adam(params=model.parameters(), lr=1e-3) lowerCAmelCase__ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) lowerCAmelCase__, lowerCAmelCase__ = dummy_dataloaders() lowerCAmelCase__ = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline lowerCAmelCase__ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert param_device.type == accelerator.device.type lowerCAmelCase__ = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
628
0
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(lowerCAmelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix SCREAMING_SNAKE_CASE_ = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements SCREAMING_SNAKE_CASE_ = [[0.0, 0.0], [0.0, 0.0]] SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = matrix[1][1], matrix[0][0] SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(lowerCAmelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(lowerCAmelCase__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule SCREAMING_SNAKE_CASE_ = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix SCREAMING_SNAKE_CASE_ = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] SCREAMING_SNAKE_CASE_ = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) SCREAMING_SNAKE_CASE_ = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) SCREAMING_SNAKE_CASE_ = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) SCREAMING_SNAKE_CASE_ = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) SCREAMING_SNAKE_CASE_ = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) SCREAMING_SNAKE_CASE_ = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) SCREAMING_SNAKE_CASE_ = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) SCREAMING_SNAKE_CASE_ = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) SCREAMING_SNAKE_CASE_ = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) SCREAMING_SNAKE_CASE_ = array(lowerCAmelCase__ ) for i in range(3 ): for j in range(3 ): SCREAMING_SNAKE_CASE_ = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix SCREAMING_SNAKE_CASE_ = array(lowerCAmelCase__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(lowerCAmelCase__ ) # Calculate the inverse of the matrix return [[float(d(lowerCAmelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
714
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class snake_case ( __lowercase ): UpperCAmelCase__ = (DDIMParallelScheduler,) UpperCAmelCase__ = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def _lowercase (self ): """simple docstring""" for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def _lowercase (self ): """simple docstring""" for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , sample_max_value=SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.1_47_71 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.3_24_60 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = 10, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE_ = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 11_47.79_04 ) < 1e-2 assert abs(result_mean.item() - 0.49_82 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop() SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_72.00_67 ) < 1e-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 52.53_02 ) < 1e-2 assert abs(result_mean.item() - 0.06_84 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.82_95 ) < 1e-2 assert abs(result_mean.item() - 0.19_51 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.07_84 ) < 1e-2 assert abs(result_mean.item() - 0.19_41 ) < 1e-3
628
0
"""simple docstring""" import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml lowerCAmelCase__ = logging.get_logger(__name__) def _lowerCamelCase ( __a, __a ): def run_func(__a ): @wraps(__A ) def run_in_eager_mode(*__a, **__a ): return func(*__A, **__A ) @wraps(__A ) @tf.function(experimental_compile=__A ) def run_in_graph_mode(*__a, **__a ): return func(*__A, **__A ) if do_eager_mode is True: if use_xla is not False: raise ValueError( '''Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.''' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = random.Random() SCREAMING_SNAKE_CASE_ = [rng.randint(0, vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(__A, shape=(batch_size, sequence_length), dtype=tf.intaa ) class snake_case ( __lowerCAmelCase ): UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = '''TensorFlow''' @property def _lowercase (self ): """simple docstring""" return tf.__version__ def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) SCREAMING_SNAKE_CASE_ = self._prepare_inference_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_speed(_inference ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) SCREAMING_SNAKE_CASE_ = self._prepare_train_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_speed(_train ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) SCREAMING_SNAKE_CASE_ = self._prepare_inference_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_memory(_inference ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) SCREAMING_SNAKE_CASE_ = self._prepare_train_func(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return self._measure_memory(_train ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) SCREAMING_SNAKE_CASE_ = ( hasattr(_UpperCamelCase , '''architectures''' ) and isinstance(config.architectures , _UpperCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE_ = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE_ = __import__('''transformers''' , fromlist=[model_class] ) SCREAMING_SNAKE_CASE_ = getattr(_UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE_ = model_cls(_UpperCamelCase ) except ImportError: raise ImportError( f'{model_class} does not exist. If you just want to test the pretrained model, you might want to' ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: SCREAMING_SNAKE_CASE_ = TF_MODEL_MAPPING[config.__class__](_UpperCamelCase ) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE_ = config.vocab_size if hasattr(_UpperCamelCase , '''vocab_size''' ) else config.encoder.vocab_size SCREAMING_SNAKE_CASE_ = random_input_ids(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(_UpperCamelCase , decoder_input_ids=_UpperCamelCase , training=_UpperCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(_UpperCamelCase , training=_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('''Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.''' ) if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) SCREAMING_SNAKE_CASE_ = ( hasattr(_UpperCamelCase , '''architectures''' ) and isinstance(config.architectures , _UpperCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE_ = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE_ = __import__('''transformers''' , fromlist=[model_class] ) SCREAMING_SNAKE_CASE_ = getattr(_UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE_ = model_cls(_UpperCamelCase ) except ImportError: raise ImportError( f'{model_class} does not exist. If you just want to test the pretrained model, you might want to' ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: SCREAMING_SNAKE_CASE_ = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_UpperCamelCase ) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE_ = config.vocab_size if hasattr(_UpperCamelCase , '''vocab_size''' ) else config.encoder.vocab_size SCREAMING_SNAKE_CASE_ = random_input_ids(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): SCREAMING_SNAKE_CASE_ = model(_UpperCamelCase , decoder_input_ids=_UpperCamelCase , labels=_UpperCamelCase , training=_UpperCamelCase )[0] SCREAMING_SNAKE_CASE_ = tf.gradients(_UpperCamelCase , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): SCREAMING_SNAKE_CASE_ = model(_UpperCamelCase , labels=_UpperCamelCase , training=_UpperCamelCase )[0] SCREAMING_SNAKE_CASE_ = tf.gradients(_UpperCamelCase , model.trainable_variables ) return gradients SCREAMING_SNAKE_CASE_ = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('''Do inference on TPU. Running model 5 times to stabilize compilation''' ) timeit.repeat(_UpperCamelCase , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average SCREAMING_SNAKE_CASE_ = timeit.repeat( _UpperCamelCase , repeat=self.args.repeat , number=10 , ) return min(_UpperCamelCase ) / 10.0 except ResourceExhaustedError as e: self.print_fn(f'Doesn\'t fit on GPU. {e}' ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" logger.info( '''Note that TensorFlow allocates more memory than ''' '''it might need to speed up computation. ''' '''The memory reported here corresponds to the memory ''' '''reported by `nvidia-smi`, which can vary depending ''' '''on total available memory on the GPU that is used.''' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '''`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory''' ''' consumption line by line.''' ) SCREAMING_SNAKE_CASE_ = start_memory_tracing('''transformers''' ) if self.args.is_tpu: # tpu raise NotImplementedError( '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking''' ''' with `args.memory=False`''' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( '''py3nvml not installed, we won\'t log GPU memory usage. ''' '''Install py3nvml (pip install py3nvml) to log information about GPU.''' ) SCREAMING_SNAKE_CASE_ = """N/A""" else: logger.info( '''Measuring total GPU usage on GPU device. Make sure to not have additional processes''' ''' running on the same GPU.''' ) # init nvml nvml.nvmlInit() func() SCREAMING_SNAKE_CASE_ = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) SCREAMING_SNAKE_CASE_ = nvml.nvmlDeviceGetMemoryInfo(_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = meminfo.used SCREAMING_SNAKE_CASE_ = Memory(_UpperCamelCase ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( '''When enabling line by line tracing, the max peak memory for CPU is inaccurate in''' ''' TensorFlow.''' ) SCREAMING_SNAKE_CASE_ = None else: SCREAMING_SNAKE_CASE_ = measure_peak_memory_cpu(_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = Memory(_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else memory_bytes if self.args.trace_memory_line_by_line: SCREAMING_SNAKE_CASE_ = stop_memory_tracing(_UpperCamelCase ) if memory is None: SCREAMING_SNAKE_CASE_ = summary.total else: SCREAMING_SNAKE_CASE_ = None return memory, summary except ResourceExhaustedError as e: self.print_fn(f'Doesn\'t fit on GPU. {e}' ) return "N/A", None
715
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = TransfoXLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''<unk> UNwanted , running''' SCREAMING_SNAKE_CASE_ = '''<unk> unwanted, running''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [0, 4, 8, 7] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' SCREAMING_SNAKE_CASE_ = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = len(SCREAMING_SNAKE_CASE_ ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
628
0
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) SCREAMING_SNAKE_CASE_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) SCREAMING_SNAKE_CASE_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def _lowercase (self ): """simple docstring""" print(f'Found {torch.cuda.device_count()} devices.' ) SCREAMING_SNAKE_CASE_ = ['torchrun', f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def _lowercase (self ): """simple docstring""" print(f'Found {torch.cuda.device_count()} devices.' ) SCREAMING_SNAKE_CASE_ = ['torchrun', f'--nproc_per_node={torch.cuda.device_count()}', self.operation_file_path] print(f'Command: {cmd}' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ['torchrun', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def _lowercase (self ): """simple docstring""" print(f'Found {torch.cuda.device_count()} devices, using 2 devices only' ) SCREAMING_SNAKE_CASE_ = ['torchrun', f'--nproc_per_node={torch.cuda.device_count()}', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(_A , env=os.environ.copy() ) if __name__ == "__main__": lowerCAmelCase__ = Accelerator() lowerCAmelCase__ = (accelerator.state.process_index + 2, 10) lowerCAmelCase__ = torch.randint(0, 10, shape).to(accelerator.device) lowerCAmelCase__ = '' lowerCAmelCase__ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowerCAmelCase__ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowerCAmelCase__ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
716
"""simple docstring""" from __future__ import annotations import typing from collections import Counter def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__a, max_perimeter + 1 ): SCREAMING_SNAKE_CASE_ = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__a ): SCREAMING_SNAKE_CASE_ = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _lowerCamelCase ( __a = 1_000 ): SCREAMING_SNAKE_CASE_ = pythagorean_triple(__a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
628
0
"""simple docstring""" import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 0 @slow def _lowercase (self ): """simple docstring""" for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(__lowerCamelCase ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(__lowerCamelCase ) , 0 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) # Check that tokenizer_type ≠ model_type SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , config=__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(__lowerCamelCase , '''vocab.txt''' ) ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , tokenizer_type='''bert''' , use_fast=__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(__lowerCamelCase , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(__lowerCamelCase , '''merges.txt''' ) ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , tokenizer_type='''gpt2''' , use_fast=__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) @require_tokenizers def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(__lowerCamelCase , '''vocab.txt''' ) ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , tokenizer_type='''bert''' ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(__lowerCamelCase , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(__lowerCamelCase , '''merges.txt''' ) ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , tokenizer_type='''gpt2''' ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) def _lowercase (self ): """simple docstring""" with pytest.raises(__lowerCamelCase ): AutoTokenizer.from_pretrained('''./''' , tokenizer_type='''xxx''' ) @require_tokenizers def _lowercase (self ): """simple docstring""" for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: SCREAMING_SNAKE_CASE_ = tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased''' ) self.assertIsInstance(__lowerCamelCase , (BertTokenizer, BertTokenizerFast) ) if isinstance(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , __lowerCamelCase ) else: self.assertEqual(tokenizer.do_lower_case , __lowerCamelCase ) self.assertEqual(tokenizer.model_max_length , 5_12 ) @require_tokenizers def _lowercase (self ): """simple docstring""" for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( __lowerCamelCase , '''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier''' , ): SCREAMING_SNAKE_CASE_ = tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists''' ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TOKENIZER_MAPPING.values() SCREAMING_SNAKE_CASE_ = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(__lowerCamelCase ) @require_tokenizers def _lowercase (self ): """simple docstring""" self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=__lowerCamelCase ) , __lowerCamelCase ) self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' ) , __lowerCamelCase ) @require_tokenizers def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''distilbert-base-uncased''' , do_lower_case=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = "Hello, world. How are you?" SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(__lowerCamelCase ) self.assertEqual('''[UNK]''' , tokens[0] ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''microsoft/mpnet-base''' , do_lower_case=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(__lowerCamelCase ) self.assertEqual('''[UNK]''' , tokens[0] ) @require_tokenizers def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config''' ) self.assertEqual(type(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(tokenizer.model_max_length , 5_12 ) self.assertEqual(tokenizer.vocab_size , 3_00_00 ) self.assertEqual(tokenizer.unk_token , '''[UNK]''' ) self.assertEqual(tokenizer.padding_side , '''right''' ) self.assertEqual(tokenizer.truncation_side , '''right''' ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''ctrl''' ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = get_tokenizer_config('''bert-base-cased''' ) SCREAMING_SNAKE_CASE_ = config.pop('''_commit_hash''' , __lowerCamelCase ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(__lowerCamelCase , {'''do_lower_case''': False} ) # This model does not have a tokenizer_config so we get back an empty dict. SCREAMING_SNAKE_CASE_ = get_tokenizer_config(__lowerCamelCase ) self.assertDictEqual(__lowerCamelCase , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = get_tokenizer_config(__lowerCamelCase ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config['''tokenizer_class'''] , '''BertTokenizer''' ) def _lowercase (self ): """simple docstring""" try: AutoConfig.register('''custom''' , __lowerCamelCase ) AutoTokenizer.register(__lowerCamelCase , slow_tokenizer_class=__lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__lowerCamelCase ): AutoTokenizer.register(__lowerCamelCase , slow_tokenizer_class=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = CustomTokenizer.from_pretrained(__lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def _lowercase (self ): """simple docstring""" try: AutoConfig.register('''custom''' , __lowerCamelCase ) # Can register in two steps AutoTokenizer.register(__lowerCamelCase , slow_tokenizer_class=__lowerCamelCase ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(__lowerCamelCase , fast_tokenizer_class=__lowerCamelCase ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( __lowerCamelCase , slow_tokenizer_class=__lowerCamelCase , fast_tokenizer_class=__lowerCamelCase ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__lowerCamelCase ): AutoTokenizer.register(__lowerCamelCase , fast_tokenizer_class=__lowerCamelCase ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ = BertTokenizerFast.from_pretrained(__lowerCamelCase ) bert_tokenizer.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = CustomTokenizerFast.from_pretrained(__lowerCamelCase ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , use_fast=__lowerCamelCase ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def _lowercase (self ): """simple docstring""" with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=__lowerCamelCase ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , trust_remote_code=__lowerCamelCase ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=__lowerCamelCase , use_fast=__lowerCamelCase ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , trust_remote_code=__lowerCamelCase , use_fast=__lowerCamelCase ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) @require_tokenizers def _lowercase (self ): """simple docstring""" class snake_case ( _A ): UpperCAmelCase__ = False class snake_case ( _A ): UpperCAmelCase__ = NewTokenizer UpperCAmelCase__ = False try: AutoConfig.register('''custom''' , __lowerCamelCase ) AutoTokenizer.register(__lowerCamelCase , slow_tokenizer_class=__lowerCamelCase ) AutoTokenizer.register(__lowerCamelCase , fast_tokenizer_class=__lowerCamelCase ) # If remote code is not set, the default is to use local SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , use_fast=__lowerCamelCase ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=__lowerCamelCase ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=__lowerCamelCase , use_fast=__lowerCamelCase ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=__lowerCamelCase ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertTrue(tokenizer.special_attribute_present ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=__lowerCamelCase , use_fast=__lowerCamelCase ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=__lowerCamelCase ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=__lowerCamelCase , use_fast=__lowerCamelCase ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) def _lowercase (self ): """simple docstring""" with self.assertRaisesRegex( __lowerCamelCase , '''bert-base is not a local folder and is not a valid model identifier''' ): SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''bert-base''' ) def _lowercase (self ): """simple docstring""" with self.assertRaisesRegex( __lowerCamelCase , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(__lowerCamelCase , revision='''aaaaaa''' ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
717
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _lowerCamelCase ( __a ): if is_torch_version('''<''', '''2.0.0''' ) or not hasattr(__a, '''_dynamo''' ): return False return isinstance(__a, torch._dynamo.eval_frame.OptimizedModule ) def _lowerCamelCase ( __a, __a = True ): SCREAMING_SNAKE_CASE_ = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE_ = is_compiled_module(__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE_ = getattr(__a, '''forward''' ) SCREAMING_SNAKE_CASE_ = model.__dict__.pop('''_original_forward''', __a ) if original_forward is not None: while hasattr(__a, '''__wrapped__''' ): SCREAMING_SNAKE_CASE_ = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE_ = forward if getattr(__a, '''_converted_to_transformer_engine''', __a ): convert_model(__a, to_transformer_engine=__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = compiled_model return model def _lowerCamelCase ( ): PartialState().wait_for_everyone() def _lowerCamelCase ( __a, __a ): if PartialState().distributed_type == DistributedType.TPU: xm.save(__a, __a ) elif PartialState().local_process_index == 0: torch.save(__a, __a ) @contextmanager def _lowerCamelCase ( **__a ): for key, value in kwargs.items(): SCREAMING_SNAKE_CASE_ = str(__a ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _lowerCamelCase ( __a ): if not hasattr(__a, '''__qualname__''' ) and not hasattr(__a, '''__name__''' ): SCREAMING_SNAKE_CASE_ = getattr(__a, '''__class__''', __a ) if hasattr(__a, '''__qualname__''' ): return obj.__qualname__ if hasattr(__a, '''__name__''' ): return obj.__name__ return str(__a ) def _lowerCamelCase ( __a, __a ): for key, value in source.items(): if isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = destination.setdefault(__a, {} ) merge_dicts(__a, __a ) else: SCREAMING_SNAKE_CASE_ = value return destination def _lowerCamelCase ( __a = None ): if port is None: SCREAMING_SNAKE_CASE_ = 29_500 with socket.socket(socket.AF_INET, socket.SOCK_STREAM ) as s: return s.connect_ex(('''localhost''', port) ) == 0
628
0
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowerCAmelCase__ = imread(r'digital_image_processing/image_data/lena_small.jpg') lowerCAmelCase__ = cvtColor(img, COLOR_BGR2GRAY) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = cn.convert_to_negative(a_ ) # assert negative_img array for at least one True assert negative_img.any() def _lowerCamelCase ( ): with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(a_, 110 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = canny.gen_gaussian_kernel(9, sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = imread('''digital_image_processing/image_data/lena_small.jpg''', 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE_ = canny.canny(a_ ) # assert canny array for at least one True assert canny_array.any() def _lowerCamelCase ( ): assert gg.gaussian_filter(a_, 5, sigma=0.9 ).all() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = array([[0.2_5, 0.5, 0.2_5], [0.5, -3, 0.5], [0.2_5, 0.5, 0.2_5]] ) SCREAMING_SNAKE_CASE_ = conv.img_convolve(a_, a_ ).astype(a_ ) assert res.any() def _lowerCamelCase ( ): assert med.median_filter(a_, 3 ).any() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = sob.sobel_filter(a_ ) assert grad.any() and theta.any() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = sp.make_sepia(a_, 20 ) assert sepia.all() def _lowerCamelCase ( __a = "digital_image_processing/image_data/lena_small.jpg" ): SCREAMING_SNAKE_CASE_ = bs.Burkes(imread(a_, 1 ), 120 ) burkes.process() assert burkes.output_img.any() def _lowerCamelCase ( __a = "digital_image_processing/image_data/lena_small.jpg", ): SCREAMING_SNAKE_CASE_ = rs.NearestNeighbour(imread(a_, 1 ), 400, 200 ) nn.process() assert nn.output.any() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE_ = imread(a_, 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE_ = lbp.get_neighbors_pixel( a_, a_, a_, a_ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE_ = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0, image.shape[0] ): for j in range(0, image.shape[1] ): SCREAMING_SNAKE_CASE_ = lbp.local_binary_value(a_, a_, a_ ) assert lbp_image.any()
718
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = CTRLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE_ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
628
0
"""simple docstring""" import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {'''vocab_file''': '''vocab.txt''', '''emoji_file''': '''emoji.json'''} lowerCAmelCase__ = { '''vocab_file''': { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt''', }, '''emoji_file''': { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json''', }, } lowerCAmelCase__ = { '''abeja/gpt-neox-japanese-2.7b''': 2048, } def _lowerCamelCase ( __a, __a ): with open(_A, '''r''', encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ = json.loads(f.read() ) SCREAMING_SNAKE_CASE_ = collections.OrderedDict() SCREAMING_SNAKE_CASE_ = collections.OrderedDict() SCREAMING_SNAKE_CASE_ = collections.OrderedDict() with open(_A, '''r''', encoding='''utf-8''' ) as f: SCREAMING_SNAKE_CASE_ = f.readlines() SCREAMING_SNAKE_CASE_ = [[t.rstrip('''\n''' )] if (t == ''',''' or ''',''' not in t) else t.rstrip('''\n''' ).split(''',''' ) for t in token] for idx, b in enumerate(_A ): SCREAMING_SNAKE_CASE_ = b SCREAMING_SNAKE_CASE_ = idx for wd in b: SCREAMING_SNAKE_CASE_ = idx return vocab, raw_vocab, ids_to_tokens, emoji class snake_case ( _UpperCAmelCase ): UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = ['input_ids', 'attention_mask'] def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="<|endoftext|>" , SCREAMING_SNAKE_CASE_="<|endoftext|>" , SCREAMING_SNAKE_CASE_="<|startoftext|>" , SCREAMING_SNAKE_CASE_="<|endoftext|>" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__( unk_token=__UpperCamelCase , pad_token=__UpperCamelCase , bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , do_clean_text=__UpperCamelCase , **__UpperCamelCase , ) if not os.path.isfile(__UpperCamelCase ): raise ValueError( f'Can\'t find a vocabulary file at path \'{vocab_file}\'. To load the vocabulary from a Google pretrained' ''' model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''' ) if not os.path.isfile(__UpperCamelCase ): raise ValueError( f'Can\'t find a emoji file at path \'{emoji_file}\'. To load the emoji information from a Google' ''' pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`''' ) SCREAMING_SNAKE_CASE_ = do_clean_text SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = load_vocab_and_emoji(__UpperCamelCase , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji ) @property def _lowercase (self ): """simple docstring""" return len(self.raw_vocab ) def _lowercase (self ): """simple docstring""" return dict(self.raw_vocab , **self.added_tokens_encoder ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.subword_tokenizer.tokenize(__UpperCamelCase , clean=self.do_clean_text ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.vocab.get(__UpperCamelCase , self.vocab.get(self.unk_token ) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.subword_tokenizer.convert_id_to_token(__UpperCamelCase ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ''''''.join(__UpperCamelCase ).strip() return out_string def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__UpperCamelCase , add_special_tokens=__UpperCamelCase ) + [self.eos_token_id] ) if len(__UpperCamelCase ) > self.model_max_length: SCREAMING_SNAKE_CASE_ = input_ids[-self.model_max_length :] return input_ids def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 0 if os.path.isdir(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = os.path.join( __UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE_ = os.path.join( __UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''emoji_file'''] ) else: SCREAMING_SNAKE_CASE_ = ( (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE_ = ( (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory + VOCAB_FILES_NAMES['''emoji_file'''] ) with open(__UpperCamelCase , '''w''' , encoding='''utf-8''' ) as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( f'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.' ''' Please check that the vocabulary is not corrupted!''' ) SCREAMING_SNAKE_CASE_ = token_index writer.write(''','''.join(__UpperCamelCase ) + '''\n''' ) index += 1 with open(__UpperCamelCase , '''w''' , encoding='''utf-8''' ) as writer: json.dump(self.emoji , __UpperCamelCase ) return vocab_file, emoji_file class snake_case ( _UpperCAmelCase ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = vocab # same as swe SCREAMING_SNAKE_CASE_ = ids_to_tokens # same as bpe SCREAMING_SNAKE_CASE_ = emoji SCREAMING_SNAKE_CASE_ = np.max([len(__UpperCamelCase ) for w in self.vocab.keys()] ) SCREAMING_SNAKE_CASE_ = re.compile(R'''(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)''' ) SCREAMING_SNAKE_CASE_ = re.compile(R'''[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*''' ) SCREAMING_SNAKE_CASE_ = re.compile(R'''[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}''' ) SCREAMING_SNAKE_CASE_ = re.compile( R'''([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''' ) SCREAMING_SNAKE_CASE_ = re.compile( R'''(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*''' ) SCREAMING_SNAKE_CASE_ = re.compile( R'''((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*''' ) SCREAMING_SNAKE_CASE_ = '''─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿''' SCREAMING_SNAKE_CASE_ = '''▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟''' SCREAMING_SNAKE_CASE_ = str.maketrans({k: '''<BLOCK>''' for k in keisen + blocks} ) def __len__(self ): """simple docstring""" return len(self.ids_to_tokens ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.content_repattera.sub('''<URL>''' , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.content_repattera.sub('''<EMAIL>''' , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.content_repattera.sub('''<TEL>''' , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.content_repattera.sub('''<DATE>''' , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.content_repattera.sub('''<DATE>''' , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = self.content_repattera.sub('''<PRICE>''' , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: SCREAMING_SNAKE_CASE_ = content.replace('''<BLOCK><BLOCK>''' , '''<BLOCK>''' ) return content def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ = text.replace(''' ''' , '''<SP>''' ) SCREAMING_SNAKE_CASE_ = text.replace(''' ''' , '''<SP>''' ) SCREAMING_SNAKE_CASE_ = text.replace('''\r\n''' , '''<BR>''' ) SCREAMING_SNAKE_CASE_ = text.replace('''\n''' , '''<BR>''' ) SCREAMING_SNAKE_CASE_ = text.replace('''\r''' , '''<BR>''' ) SCREAMING_SNAKE_CASE_ = text.replace('''\t''' , '''<TAB>''' ) SCREAMING_SNAKE_CASE_ = text.replace('''—''' , '''ー''' ) SCREAMING_SNAKE_CASE_ = text.replace('''−''' , '''ー''' ) for k, v in self.emoji["emoji"].items(): if k in text: SCREAMING_SNAKE_CASE_ = text.replace(__UpperCamelCase , __UpperCamelCase ) if clean: SCREAMING_SNAKE_CASE_ = self.clean_text(__UpperCamelCase ) def check_simbol(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = x.encode() if len(__UpperCamelCase ) == 1 and len(__UpperCamelCase ) == 2: SCREAMING_SNAKE_CASE_ = (int(e[0] ) << 8) + int(e[1] ) if ( (c >= 0XC2A1 and c <= 0XC2BF) or (c >= 0XC780 and c <= 0XC783) or (c >= 0XCAB9 and c <= 0XCBBF) or (c >= 0XCC80 and c <= 0XCDA2) ): return True return False def checkuae(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = x.encode() if len(__UpperCamelCase ) == 1 and len(__UpperCamelCase ) == 3: SCREAMING_SNAKE_CASE_ = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0XE28080 and c <= 0XE2B07F: return True return False SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = [] while pos < len(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = min(len(__UpperCamelCase ) , pos + self.maxlen + 1 ) if text[pos] == '''<''' else pos + 3 SCREAMING_SNAKE_CASE_ = [] # (token_id, token, pos) for e in range(__UpperCamelCase , __UpperCamelCase , -1 ): SCREAMING_SNAKE_CASE_ = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(__UpperCamelCase ) > 2: SCREAMING_SNAKE_CASE_ = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(__UpperCamelCase ) > 0: # the smallest token_id is adopted SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = sorted(__UpperCamelCase , key=lambda SCREAMING_SNAKE_CASE_ : x[0] )[0] result.append(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = e else: SCREAMING_SNAKE_CASE_ = pos + 1 SCREAMING_SNAKE_CASE_ = text[pos:end] if check_simbol(__UpperCamelCase ): result.append('''<KIGOU>''' ) elif checkuae(__UpperCamelCase ): result.append('''<U2000U2BFF>''' ) else: for i in wd.encode('''utf-8''' ): result.append('''<|byte%d|>''' % i ) SCREAMING_SNAKE_CASE_ = end return result def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="\n" ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(__UpperCamelCase ) > 0: words.append(bytearray(__UpperCamelCase ).decode('''utf-8''' , errors='''replace''' ) ) SCREAMING_SNAKE_CASE_ = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji['''emoji_inv'''][word] ) elif word == "<SP>": words.append(''' ''' ) elif word == "<BR>": words.append(__UpperCamelCase ) elif word == "<TAB>": words.append('''\t''' ) elif word == "<BLOCK>": words.append('''▀''' ) elif word == "<KIGOU>": words.append('''ǀ''' ) elif word == "<U2000U2BFF>": words.append('''‖''' ) else: words.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: words.append(bytearray(__UpperCamelCase ).decode('''utf-8''' , errors='''replace''' ) ) SCREAMING_SNAKE_CASE_ = ''''''.join(__UpperCamelCase ) return text
719
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a, __a ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_ = BigBirdConfig.from_json_file(__a ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: SCREAMING_SNAKE_CASE_ = BigBirdForQuestionAnswering(__a ) else: SCREAMING_SNAKE_CASE_ = BigBirdForPreTraining(__a ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__a, __a, is_trivia_qa=__a ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) 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( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
628
0
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 lowerCAmelCase__ = sys.version_info >= (3, 10) def _lowerCamelCase ( __a=None, __a=None ): return field(default_factory=lambda: default, metadata=__a ) @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = field(default='''toto''' , metadata={'''help''': '''help message'''} ) @dataclass class snake_case : UpperCAmelCase__ = False UpperCAmelCase__ = True UpperCAmelCase__ = None class snake_case ( _a ): UpperCAmelCase__ = """titi""" UpperCAmelCase__ = """toto""" class snake_case ( _a ): UpperCAmelCase__ = """titi""" UpperCAmelCase__ = """toto""" UpperCAmelCase__ = 42 @dataclass class snake_case : UpperCAmelCase__ = "toto" def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = BasicEnum(self.foo ) @dataclass class snake_case : UpperCAmelCase__ = "toto" def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = MixedTypeEnum(self.foo ) @dataclass class snake_case : UpperCAmelCase__ = None UpperCAmelCase__ = field(default=_a , metadata={'''help''': '''help message'''} ) UpperCAmelCase__ = None UpperCAmelCase__ = list_field(default=[] ) UpperCAmelCase__ = list_field(default=[] ) @dataclass class snake_case : UpperCAmelCase__ = list_field(default=[] ) UpperCAmelCase__ = list_field(default=[1, 2, 3] ) UpperCAmelCase__ = list_field(default=['''Hallo''', '''Bonjour''', '''Hello'''] ) UpperCAmelCase__ = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class snake_case : UpperCAmelCase__ = field() UpperCAmelCase__ = field() UpperCAmelCase__ = field() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = BasicEnum(self.required_enum ) @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = field() UpperCAmelCase__ = None UpperCAmelCase__ = field(default='''toto''' , metadata={'''help''': '''help message'''} ) UpperCAmelCase__ = list_field(default=['''Hallo''', '''Bonjour''', '''Hello'''] ) if is_python_no_less_than_3_10: @dataclass class snake_case : UpperCAmelCase__ = False UpperCAmelCase__ = True UpperCAmelCase__ = None @dataclass class snake_case : UpperCAmelCase__ = None UpperCAmelCase__ = field(default=_a , metadata={'''help''': '''help message'''} ) UpperCAmelCase__ = None UpperCAmelCase__ = list_field(default=[] ) UpperCAmelCase__ = list_field(default=[] ) class snake_case ( unittest.TestCase ): def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): SCREAMING_SNAKE_CASE_ = {k: v for k, v in vars(snake_case_ ).items() if k != '''container'''} SCREAMING_SNAKE_CASE_ = {k: v for k, v in vars(snake_case_ ).items() if k != '''container'''} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get('''choices''' , snake_case_ ) and yy.get('''choices''' , snake_case_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx['''type'''](snake_case_ ) , yy['''type'''](snake_case_ ) ) del xx["type"], yy["type"] self.assertEqual(snake_case_ , snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument('''--foo''' , type=snake_case_ , required=snake_case_ ) expected.add_argument('''--bar''' , type=snake_case_ , required=snake_case_ ) expected.add_argument('''--baz''' , type=snake_case_ , required=snake_case_ ) expected.add_argument('''--flag''' , type=snake_case_ , default=snake_case_ , const=snake_case_ , nargs='''?''' ) self.argparsersEqual(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = ['''--foo''', '''1''', '''--baz''', '''quux''', '''--bar''', '''0.5'''] ((SCREAMING_SNAKE_CASE_ ) , ) = parser.parse_args_into_dataclasses(snake_case_ , look_for_args_file=snake_case_ ) self.assertFalse(example.flag ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument('''--foo''' , default=42 , type=snake_case_ ) expected.add_argument('''--baz''' , default='''toto''' , type=snake_case_ , help='''help message''' ) self.argparsersEqual(snake_case_ , snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument('''--foo''' , type=snake_case_ , default=snake_case_ , const=snake_case_ , nargs='''?''' ) expected.add_argument('''--baz''' , type=snake_case_ , default=snake_case_ , const=snake_case_ , nargs='''?''' ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument('''--no_baz''' , action='''store_false''' , default=snake_case_ , dest='''baz''' ) expected.add_argument('''--opt''' , type=snake_case_ , default=snake_case_ ) SCREAMING_SNAKE_CASE_ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(snake_case_ ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) self.argparsersEqual(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = parser.parse_args([] ) self.assertEqual(snake_case_ , Namespace(foo=snake_case_ , baz=snake_case_ , opt=snake_case_ ) ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''--no_baz'''] ) self.assertEqual(snake_case_ , Namespace(foo=snake_case_ , baz=snake_case_ , opt=snake_case_ ) ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''--baz'''] ) self.assertEqual(snake_case_ , Namespace(foo=snake_case_ , baz=snake_case_ , opt=snake_case_ ) ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''True''', '''--baz''', '''True''', '''--opt''', '''True'''] ) self.assertEqual(snake_case_ , Namespace(foo=snake_case_ , baz=snake_case_ , opt=snake_case_ ) ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''False''', '''--baz''', '''False''', '''--opt''', '''False'''] ) self.assertEqual(snake_case_ , Namespace(foo=snake_case_ , baz=snake_case_ , opt=snake_case_ ) ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument( '''--foo''' , default='''toto''' , choices=['''titi''', '''toto''', 42] , type=make_choice_type_function(['''titi''', '''toto''', 42] ) , ) self.argparsersEqual(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = parser.parse_args([] ) self.assertEqual(args.foo , '''toto''' ) SCREAMING_SNAKE_CASE_ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''titi'''] ) self.assertEqual(args.foo , '''titi''' ) SCREAMING_SNAKE_CASE_ = parser.parse_args_into_dataclasses(['''--foo''', '''titi'''] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''42'''] ) self.assertEqual(args.foo , 42 ) SCREAMING_SNAKE_CASE_ = parser.parse_args_into_dataclasses(['''--foo''', '''42'''] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def _lowercase (self ): """simple docstring""" @dataclass class snake_case : UpperCAmelCase__ = "toto" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument( '''--foo''' , default='''toto''' , choices=('''titi''', '''toto''', 42) , type=make_choice_type_function(['''titi''', '''toto''', 42] ) , ) self.argparsersEqual(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = parser.parse_args([] ) self.assertEqual(args.foo , '''toto''' ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''titi'''] ) self.assertEqual(args.foo , '''titi''' ) SCREAMING_SNAKE_CASE_ = parser.parse_args(['''--foo''', '''42'''] ) self.assertEqual(args.foo , 42 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument('''--foo_int''' , nargs='''+''' , default=[] , type=snake_case_ ) expected.add_argument('''--bar_int''' , nargs='''+''' , default=[1, 2, 3] , type=snake_case_ ) expected.add_argument('''--foo_str''' , nargs='''+''' , default=['''Hallo''', '''Bonjour''', '''Hello'''] , type=snake_case_ ) expected.add_argument('''--foo_float''' , nargs='''+''' , default=[0.1, 0.2, 0.3] , type=snake_case_ ) self.argparsersEqual(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = parser.parse_args([] ) self.assertEqual( snake_case_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=['''Hallo''', '''Bonjour''', '''Hello'''] , foo_float=[0.1, 0.2, 0.3] ) , ) SCREAMING_SNAKE_CASE_ = parser.parse_args('''--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7'''.split() ) self.assertEqual(snake_case_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=['''a''', '''b''', '''c'''] , foo_float=[0.1, 0.7] ) ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument('''--foo''' , default=snake_case_ , type=snake_case_ ) expected.add_argument('''--bar''' , default=snake_case_ , type=snake_case_ , help='''help message''' ) expected.add_argument('''--baz''' , default=snake_case_ , type=snake_case_ ) expected.add_argument('''--ces''' , nargs='''+''' , default=[] , type=snake_case_ ) expected.add_argument('''--des''' , nargs='''+''' , default=[] , type=snake_case_ ) SCREAMING_SNAKE_CASE_ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(snake_case_ ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) self.argparsersEqual(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = parser.parse_args([] ) self.assertEqual(snake_case_ , Namespace(foo=snake_case_ , bar=snake_case_ , baz=snake_case_ , ces=[] , des=[] ) ) SCREAMING_SNAKE_CASE_ = parser.parse_args('''--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3'''.split() ) self.assertEqual(snake_case_ , Namespace(foo=12 , bar=3.14 , baz='''42''' , ces=['''a''', '''b''', '''c'''] , des=[1, 2, 3] ) ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument('''--required_list''' , nargs='''+''' , type=snake_case_ , required=snake_case_ ) expected.add_argument('''--required_str''' , type=snake_case_ , required=snake_case_ ) expected.add_argument( '''--required_enum''' , type=make_choice_type_function(['''titi''', '''toto'''] ) , choices=['''titi''', '''toto'''] , required=snake_case_ , ) self.argparsersEqual(snake_case_ , snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() expected.add_argument('''--foo''' , type=snake_case_ , required=snake_case_ ) expected.add_argument( '''--required_enum''' , type=make_choice_type_function(['''titi''', '''toto'''] ) , choices=['''titi''', '''toto'''] , required=snake_case_ , ) expected.add_argument('''--opt''' , type=snake_case_ , default=snake_case_ ) expected.add_argument('''--baz''' , default='''toto''' , type=snake_case_ , help='''help message''' ) expected.add_argument('''--foo_str''' , nargs='''+''' , default=['''Hallo''', '''Bonjour''', '''Hello'''] , type=snake_case_ ) self.argparsersEqual(snake_case_ , snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = { '''foo''': 12, '''bar''': 3.14, '''baz''': '''42''', '''flag''': True, } SCREAMING_SNAKE_CASE_ = parser.parse_dict(snake_case_ )[0] SCREAMING_SNAKE_CASE_ = BasicExample(**snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = { '''foo''': 12, '''bar''': 3.14, '''baz''': '''42''', '''flag''': True, '''extra''': 42, } self.assertRaises(snake_case_ , parser.parse_dict , snake_case_ , allow_extra_keys=snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = { '''foo''': 12, '''bar''': 3.14, '''baz''': '''42''', '''flag''': True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ = os.path.join(snake_case_ , '''temp_json''' ) os.mkdir(snake_case_ ) with open(temp_local_path + '''.json''' , '''w+''' ) as f: json.dump(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = parser.parse_yaml_file(Path(temp_local_path + '''.json''' ) )[0] SCREAMING_SNAKE_CASE_ = BasicExample(**snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) SCREAMING_SNAKE_CASE_ = { '''foo''': 12, '''bar''': 3.14, '''baz''': '''42''', '''flag''': True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ = os.path.join(snake_case_ , '''temp_yaml''' ) os.mkdir(snake_case_ ) with open(temp_local_path + '''.yaml''' , '''w+''' ) as f: yaml.dump(snake_case_ , snake_case_ ) SCREAMING_SNAKE_CASE_ = parser.parse_yaml_file(Path(temp_local_path + '''.yaml''' ) )[0] SCREAMING_SNAKE_CASE_ = BasicExample(**snake_case_ ) self.assertEqual(snake_case_ , snake_case_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = HfArgumentParser(snake_case_ ) self.assertIsNotNone(snake_case_ )
720
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name def _lowerCamelCase ( __a ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''', __a, ) if isinstance(__a, torch.Tensor ): return image elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [image] if isinstance(image[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = image[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE_ = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = np.array(__a ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = image.transpose(0, 3, 1, 2 ) SCREAMING_SNAKE_CASE_ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(image[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return image def _lowerCamelCase ( __a ): if isinstance(__a, torch.Tensor ): return mask elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [mask] if isinstance(mask[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = mask[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE_ = [np.array(m.convert('''L''' ).resize((w, h), resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(mask[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return mask class snake_case ( __lowercase ): UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 2_50 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = image SCREAMING_SNAKE_CASE_ = _preprocess_image(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = _preprocess_mask(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE_ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) SCREAMING_SNAKE_CASE_ = original_image.shape SCREAMING_SNAKE_CASE_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) SCREAMING_SNAKE_CASE_ = eta SCREAMING_SNAKE_CASE_ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE_ = generator[0] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE_ = self.scheduler.undo_step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = t SCREAMING_SNAKE_CASE_ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
628
0
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: lowerCAmelCase__ = None lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} lowerCAmelCase__ = { '''vocab_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json''' ), }, } lowerCAmelCase__ = { '''facebook/nllb-large-en-ro''': 1024, '''facebook/nllb-200-distilled-600M''': 1024, } # fmt: off lowerCAmelCase__ = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn'''] class snake_case ( SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = ['''input_ids''', '''attention_mask'''] UpperCAmelCase__ = NllbTokenizer UpperCAmelCase__ = [] UpperCAmelCase__ = [] def __init__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="</s>" , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = AddedToken(_lowercase , lstrip=_lowercase , rstrip=_lowercase ) if isinstance(_lowercase , _lowercase ) else mask_token SCREAMING_SNAKE_CASE_ = legacy_behaviour super().__init__( vocab_file=_lowercase , tokenizer_file=_lowercase , bos_token=_lowercase , eos_token=_lowercase , sep_token=_lowercase , cls_token=_lowercase , unk_token=_lowercase , pad_token=_lowercase , mask_token=_lowercase , src_lang=_lowercase , tgt_lang=_lowercase , additional_special_tokens=_lowercase , legacy_behaviour=_lowercase , **_lowercase , ) SCREAMING_SNAKE_CASE_ = vocab_file SCREAMING_SNAKE_CASE_ = False if not self.vocab_file else True SCREAMING_SNAKE_CASE_ = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens} ) SCREAMING_SNAKE_CASE_ = { lang_code: self.convert_tokens_to_ids(_lowercase ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE_ = src_lang if src_lang is not None else """eng_Latn""" SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE_ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _lowercase (self ): """simple docstring""" return self._src_lang @src_lang.setter def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): """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] def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) SCREAMING_SNAKE_CASE_ = src_lang SCREAMING_SNAKE_CASE_ = self(_lowercase , add_special_tokens=_lowercase , return_tensors=_lowercase , **_lowercase ) SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(_lowercase ) SCREAMING_SNAKE_CASE_ = tgt_lang_id return inputs def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "eng_Latn" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "fra_Latn" , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = src_lang SCREAMING_SNAKE_CASE_ = tgt_lang return super().prepare_seqaseq_batch(_lowercase , _lowercase , **_lowercase ) def _lowercase (self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _lowercase (self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(_lowercase ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE_ = [self.cur_lang_code] SCREAMING_SNAKE_CASE_ = [self.eos_token_id] SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE_ = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.convert_tokens_to_ids(_lowercase ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE_ = [self.cur_lang_code] SCREAMING_SNAKE_CASE_ = [self.eos_token_id] SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE_ = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE_ = processors.TemplateProcessing( single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str , pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): """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(_lowercase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory.' ) return SCREAMING_SNAKE_CASE_ = os.path.join( _lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowercase ): copyfile(self.vocab_file , _lowercase ) return (out_vocab_file,)
721
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a, __a ): return (preds == labels).mean() @dataclass class snake_case : UpperCAmelCase__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class snake_case : UpperCAmelCase__ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) UpperCAmelCase__ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) UpperCAmelCase__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def _lowerCamelCase ( ): # 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() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1 ), training_args.fpaa, ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''', __a ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE_ = processors[data_args.task_name]() SCREAMING_SNAKE_CASE_ = processor.get_labels() SCREAMING_SNAKE_CASE_ = len(__a ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=__a, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=__a, cache_dir=model_args.cache_dir, ) # Get datasets SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, ) if training_args.do_eval else None ) def compute_metrics(__a ) -> Dict: SCREAMING_SNAKE_CASE_ = np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(__a, p.label_ids )} # Data collator SCREAMING_SNAKE_CASE_ = DataCollatorWithPadding(__a, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE_ = Trainer( model=__a, args=__a, train_dataset=__a, eval_dataset=__a, compute_metrics=__a, data_collator=__a, ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ = trainer.evaluate() SCREAMING_SNAKE_CASE_ = os.path.join(training_args.output_dir, '''eval_results.txt''' ) if trainer.is_world_master(): with open(__a, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''', __a, __a ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__a ) return results def _lowerCamelCase ( __a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
628
0
"""simple docstring""" def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = abs(snake_case__ ) SCREAMING_SNAKE_CASE_ = 0 while n > 0: res += n % 10 n //= 10 return res def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = abs(snake_case__ ) return n if n < 10 else n % 10 + sum_of_digits(n // 10 ) def _lowerCamelCase ( __a ): return sum(int(snake_case__ ) for c in str(abs(snake_case__ ) ) ) def _lowerCamelCase ( ): from collections.abc import Callable from timeit import timeit def benchmark_a_function(__a, __a ) -> None: SCREAMING_SNAKE_CASE_ = F'{func.__name__}({value})' SCREAMING_SNAKE_CASE_ = timeit(F'__main__.{call}', setup='''import __main__''' ) print(F'{call:56} = {func(snake_case__ )} -- {timing:.4f} seconds' ) for value in (262_144, 1_125_899_906_842_624, 1_267_650_600_228_229_401_496_703_205_376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(snake_case__, snake_case__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
700
"""simple docstring""" import cva import numpy as np class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if k in (0.04, 0.06): SCREAMING_SNAKE_CASE_ = k SCREAMING_SNAKE_CASE_ = window_size else: raise ValueError('''invalid k value''' ) def __str__(self ): """simple docstring""" return str(self.k ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = cva.imread(SCREAMING_SNAKE_CASE_ , 0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = img.shape SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = img.copy() SCREAMING_SNAKE_CASE_ = cva.cvtColor(SCREAMING_SNAKE_CASE_ , cva.COLOR_GRAY2RGB ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = np.gradient(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = dx**2 SCREAMING_SNAKE_CASE_ = dy**2 SCREAMING_SNAKE_CASE_ = dx * dy SCREAMING_SNAKE_CASE_ = 0.04 SCREAMING_SNAKE_CASE_ = self.window_size // 2 for y in range(SCREAMING_SNAKE_CASE_ , h - offset ): for x in range(SCREAMING_SNAKE_CASE_ , w - offset ): SCREAMING_SNAKE_CASE_ = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = (wxx * wyy) - (wxy**2) SCREAMING_SNAKE_CASE_ = wxx + wyy SCREAMING_SNAKE_CASE_ = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": lowerCAmelCase__ = HarrisCorner(0.04, 3) lowerCAmelCase__, lowerCAmelCase__ = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
628
0
"""simple docstring""" from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def _lowerCamelCase ( __a, __a, __a = "x", __a = 10**-10, __a = 1, ): SCREAMING_SNAKE_CASE_ = symbols(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = lambdify(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = lambdify(__SCREAMING_SNAKE_CASE, diff(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ) ) SCREAMING_SNAKE_CASE_ = starting_point while True: if diff_function(__SCREAMING_SNAKE_CASE ) != 0: SCREAMING_SNAKE_CASE_ = prev_guess - multiplicity * func(__SCREAMING_SNAKE_CASE ) / diff_function( __SCREAMING_SNAKE_CASE ) else: raise ZeroDivisionError('''Could not find root''' ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess SCREAMING_SNAKE_CASE_ = next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'''The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}''') # Find root of polynomial # Find fourth Root of 5 print(f'''The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5j)}''') # Find value of e print( 'The root of log(y) - 1 = 0 is ', f'''{newton_raphson('log(y) - 1', 2, variable='y')}''', ) # Exponential Roots print( 'The root of exp(x) - 1 = 0 is', f'''{newton_raphson('exp(x) - 1', 10, precision=0.005)}''', ) # Find root of cos(x) print(f'''The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}''')
701
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class snake_case ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.text_to_image( prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = pipe.image_variation(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
628
0
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, 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.models.esm.modeling_esmfold import EsmForProteinFolding class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=19 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): """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_ = 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 _lowercase (self ): """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 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, input_mask, sequence_labels, token_labels, choice_labels def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=SCREAMING_SNAKE_CASE_ , esmfold_config={'''trunk''': {'''num_blocks''': 2}, '''fp16_esm''': False} , ) return config def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = EsmForProteinFolding(config=SCREAMING_SNAKE_CASE_ ).float() model.to(SCREAMING_SNAKE_CASE_ ) model.eval() SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def _lowercase (self ): """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_ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class snake_case ( __lowercase , __lowercase , unittest.TestCase ): UpperCAmelCase__ = False UpperCAmelCase__ = (EsmForProteinFolding,) if is_torch_available() else () UpperCAmelCase__ = () UpperCAmelCase__ = {} if is_torch_available() else {} UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = EsmFoldModelTester(self ) SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def _lowercase (self ): """simple docstring""" self.config_tester.run_common_tests() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip('''Does not support attention outputs''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip def _lowercase (self ): """simple docstring""" pass @unittest.skip('''Esm does not support embedding resizing''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''Esm does not support embedding resizing''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not support passing input embeds!''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not support head pruning.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not output hidden states in the normal way.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMfold does not output hidden states in the normal way.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold only has one output format.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''This test doesn\'t work for ESMFold and doesn\'t test core functionality''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold does not support input chunking.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support torchscript compilation.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''ESMFold doesn\'t support data parallel.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def _lowercase (self ): """simple docstring""" pass @require_torch class snake_case ( __lowercase ): @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = EsmForProteinFolding.from_pretrained('''facebook/esmfold_v1''' ).float() model.eval() SCREAMING_SNAKE_CASE_ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ )['''positions'''] SCREAMING_SNAKE_CASE_ = torch.tensor([2.58_28, 0.79_93, -10.93_34] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
702
"""simple docstring""" import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def _lowerCamelCase ( __a ): # picklable for multiprocessing return x.sum() def _lowerCamelCase ( __a ): # picklable for multiprocessing return i + 1 @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = [1, 2] SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': [1, 2], '''b''': [3, 4]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 1}, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = [2, 3] SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': [2, 3], '''b''': [4, 5]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 2}, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = 2 self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = {'''a''': np.eye(2 ), '''b''': np.zeros(3 ), '''c''': np.ones(2 )} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 0, '''c''': 2} SCREAMING_SNAKE_CASE_ = { '''a''': np.eye(2 ).astype(SCREAMING_SNAKE_CASE_ ), '''b''': np.zeros(3 ).astype(SCREAMING_SNAKE_CASE_ ), '''c''': np.ones(2 ).astype(SCREAMING_SNAKE_CASE_ ), } self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): # can't pickle a local lambda map_nested(lambda SCREAMING_SNAKE_CASE_ : x + 1 , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 3, '''b''': 4} SCREAMING_SNAKE_CASE_ = {'''a''': 5, '''b''': 6} SCREAMING_SNAKE_CASE_ = sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" class snake_case : UpperCAmelCase__ = '''bar''' SCREAMING_SNAKE_CASE_ = Foo() self.assertEqual(foo.my_attr , '''bar''' ) with temporary_assignment(SCREAMING_SNAKE_CASE_ , '''my_attr''' , '''BAR''' ): self.assertEqual(foo.my_attr , '''BAR''' ) self.assertEqual(foo.my_attr , '''bar''' ) @pytest.mark.parametrize( '''iterable_length, num_proc, expected_num_proc''', [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ], ) def _lowerCamelCase ( __a, __a, __a ): with patch('''datasets.utils.py_utils._single_map_nested''' ) as mock_single_map_nested, patch( '''datasets.parallel.parallel.Pool''' ) as mock_multiprocessing_pool: SCREAMING_SNAKE_CASE_ = {F'{i}': i for i in range(__a )} SCREAMING_SNAKE_CASE_ = map_nested(lambda __a : x + 10, __a, num_proc=__a, parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class snake_case ( __lowercase ): @require_tf def _lowercase (self ): """simple docstring""" import tensorflow as tf from tensorflow.keras import layers SCREAMING_SNAKE_CASE_ = layers.Dense(2 ) def gen_random_output(): SCREAMING_SNAKE_CASE_ = tf.random.uniform((1, 3) ) return model(SCREAMING_SNAKE_CASE_ ).numpy() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def _lowercase (self ): """simple docstring""" import torch def gen_random_output(): SCREAMING_SNAKE_CASE_ = torch.nn.Linear(3 , 2 ) SCREAMING_SNAKE_CASE_ = torch.rand(1 , 3 ) return model(SCREAMING_SNAKE_CASE_ ).detach().numpy() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def _lowercase (self ): """simple docstring""" def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize('''input_data''', [{}] ) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).data assert output_data == input_data @pytest.mark.parametrize( '''data, expected_output''', [ ({}, []), ([], []), ('''foo''', ['''foo''']), (['''foo''', '''bar'''], ['''foo''', '''bar''']), ([['''foo''', '''bar''']], ['''foo''', '''bar''']), ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']), ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']), ({'''a''': 1, '''b''': 2}, [1, 2]), ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]), ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]), ], ) def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).flatten() assert output == expected_output def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = A(x=1, y='''foobar''' ) SCREAMING_SNAKE_CASE_ = {'''x''': 1, '''y''': '''foobar'''} assert asdict(__a ) == expected_output SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': A(x=10, y='''foo''' )}, '''c''': [A(x=20, y='''bar''' )]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]} assert asdict(__a ) == expected_output with pytest.raises(__a ): asdict([1, A(x=10, y='''foo''' )] ) def _lowerCamelCase ( __a ): return text.split() def _lowerCamelCase ( __a ): yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def _lowerCamelCase ( ): with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = [] for yield_time, content in iflatmap_unordered( __a, _aseconds_generator_of_aitems_with_timing, kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__a ) assert out.count('''a''' ) == 2 assert out.count('''b''' ) == 2 assert len(__a ) == 4
628
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class snake_case ( unittest.TestCase ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=18 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=4_00 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = size if size is not None else {"shortest_edge": 20} SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE_ = parent SCREAMING_SNAKE_CASE_ = batch_size SCREAMING_SNAKE_CASE_ = num_channels SCREAMING_SNAKE_CASE_ = image_size SCREAMING_SNAKE_CASE_ = min_resolution SCREAMING_SNAKE_CASE_ = max_resolution SCREAMING_SNAKE_CASE_ = do_resize SCREAMING_SNAKE_CASE_ = size SCREAMING_SNAKE_CASE_ = do_center_crop SCREAMING_SNAKE_CASE_ = crop_size SCREAMING_SNAKE_CASE_ = do_flip_channel_order def _lowercase (self ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): UpperCAmelCase__ = MobileViTImageProcessor if is_vision_available() else None def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = MobileViTImageProcessingTester(self ) @property def _lowercase (self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__A , '''do_resize''' ) ) self.assertTrue(hasattr(__A , '''size''' ) ) self.assertTrue(hasattr(__A , '''do_center_crop''' ) ) self.assertTrue(hasattr(__A , '''center_crop''' ) ) self.assertTrue(hasattr(__A , '''do_flip_channel_order''' ) ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A ) for image in image_inputs: self.assertIsInstance(__A , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE_ = image_processing(__A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A ) for image in image_inputs: self.assertIsInstance(__A , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE_ = image_processing(__A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A ) for image in image_inputs: self.assertIsInstance(__A , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE_ = image_processing(__A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
703
"""simple docstring""" import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCAmelCase__ = { 'facebook/maskformer-swin-base-ade': ( 'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowerCAmelCase__ = logging.get_logger(__name__) class snake_case ( __lowercase ): UpperCAmelCase__ = '''maskformer''' UpperCAmelCase__ = {'''hidden_size''': '''mask_feature_size'''} UpperCAmelCase__ = ['''resnet''', '''swin'''] UpperCAmelCase__ = ['''detr'''] def __init__(self , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 20.0 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k SCREAMING_SNAKE_CASE_ = SwinConfig( image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = backbone_config.pop('''model_type''' ) SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ' f'Supported model types: {",".join(self.backbones_supported )}' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 SCREAMING_SNAKE_CASE_ = DetrConfig() else: # verify that the decoder is supported SCREAMING_SNAKE_CASE_ = ( decoder_config.pop('''model_type''' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'Transformer Decoder {decoder_type} not supported, please use one of' f' {",".join(self.decoders_supported )}' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[decoder_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = backbone_config SCREAMING_SNAKE_CASE_ = decoder_config # main feature dimension for the model SCREAMING_SNAKE_CASE_ = fpn_feature_size SCREAMING_SNAKE_CASE_ = mask_feature_size # initializer SCREAMING_SNAKE_CASE_ = init_std SCREAMING_SNAKE_CASE_ = init_xavier_std # Hungarian matcher && loss SCREAMING_SNAKE_CASE_ = cross_entropy_weight SCREAMING_SNAKE_CASE_ = dice_weight SCREAMING_SNAKE_CASE_ = mask_weight SCREAMING_SNAKE_CASE_ = use_auxiliary_loss SCREAMING_SNAKE_CASE_ = no_object_weight SCREAMING_SNAKE_CASE_ = output_auxiliary_logits SCREAMING_SNAKE_CASE_ = self.decoder_config.encoder_attention_heads SCREAMING_SNAKE_CASE_ = self.decoder_config.num_hidden_layers super().__init__(**SCREAMING_SNAKE_CASE_ ) @classmethod def _lowercase (cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return cls( backbone_config=SCREAMING_SNAKE_CASE_ , decoder_config=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ = self.decoder_config.to_dict() SCREAMING_SNAKE_CASE_ = self.__class__.model_type return output
628
0
"""simple docstring""" from __future__ import annotations lowerCAmelCase__ = list[list[int]] # assigning initial values to the grid lowerCAmelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution lowerCAmelCase__ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _lowerCamelCase ( __a, __a, __a, __a ): for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _lowerCamelCase ( __a ): for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _lowerCamelCase ( __a ): if location := find_empty_location(_lowerCamelCase ): SCREAMING_SNAKE_CASE_ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1, 10 ): if is_safe(_lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase ): SCREAMING_SNAKE_CASE_ = digit if sudoku(_lowerCamelCase ) is not None: return grid SCREAMING_SNAKE_CASE_ = 0 return None def _lowerCamelCase ( __a ): for row in grid: for cell in row: print(_lowerCamelCase, end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') lowerCAmelCase__ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
704
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] SCREAMING_SNAKE_CASE_ = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE_ = [4, 4, 4, 4] SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE_ = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE_ = 128 elif "large" in model_name: SCREAMING_SNAKE_CASE_ = 192 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE_ = 256 elif "huge" in model_name: SCREAMING_SNAKE_CASE_ = 352 # set label information SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE_ = '''imagenet-22k-id2label.json''' else: SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(__a, __a, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = FocalNetConfig( embed_dim=__a, depths=__a, focal_levels=__a, focal_windows=__a, use_conv_embed=__a, idalabel=__a, labelaid=__a, use_post_layernorm=__a, use_layerscale=__a, ) return config def _lowerCamelCase ( __a ): 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 "layers" in name: SCREAMING_SNAKE_CASE_ = '''encoder.''' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE_ = name.replace('''encoder.layers''', '''encoder.stages''' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('''downsample.proj''', '''downsample.projection''' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ = name.replace('''blocks''', '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.f''', '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.h''', '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.proj''', '''modulation.projection_out''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE_ = '''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE_ = '''layernorm.bias''' if "head" in name: SCREAMING_SNAKE_CASE_ = name.replace('''head''', '''classifier''' ) else: SCREAMING_SNAKE_CASE_ = '''focalnet.''' + name return name def _lowerCamelCase ( __a, __a, __a=False ): # fmt: off SCREAMING_SNAKE_CASE_ = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on SCREAMING_SNAKE_CASE_ = model_name_to_url[model_name] print('''Checkpoint URL: ''', __a ) SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(__a, map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = get_focalnet_config(__a ) SCREAMING_SNAKE_CASE_ = FocalNetForImageClassification(__a ) model.eval() # load state dict model.load_state_dict(__a ) # verify conversion SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = BitImageProcessor( do_resize=__a, size={'''shortest_edge''': 256}, resample=PILImageResampling.BILINEAR, do_center_crop=__a, crop_size=224, do_normalize=__a, image_mean=__a, image_std=__a, ) SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__a, stream=__a ).raw ) SCREAMING_SNAKE_CASE_ = processor(images=__a, return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE_ = image_transforms(__a ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values, __a, atol=1E-4 ) SCREAMING_SNAKE_CASE_ = model(**__a ) SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(-1 ).item() print('''Predicted class:''', model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''', outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE_ = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE_ = torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8] ) assert torch.allclose(outputs.logits[0, :3], __a, atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model and processor of {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if push_to_hub: print(F'Pushing model and processor of {model_name} to the hub...' ) model.push_to_hub(F'{model_name}' ) processor.push_to_hub(F'{model_name}' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
628
0
"""simple docstring""" import sys lowerCAmelCase__ = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = 1 for digit in s: product *= int(__a ) return product def _lowerCamelCase ( __a = N ): SCREAMING_SNAKE_CASE_ = -sys.maxsize - 1 SCREAMING_SNAKE_CASE_ = n[:13] SCREAMING_SNAKE_CASE_ = 13 while cur_index < len(__a ) - 13: if int(n[cur_index] ) >= int(substr[0] ): SCREAMING_SNAKE_CASE_ = substr[1:] + n[cur_index] cur_index += 1 else: SCREAMING_SNAKE_CASE_ = max(__a, str_eval(__a ) ) SCREAMING_SNAKE_CASE_ = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
705
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class snake_case ( __lowercase ): UpperCAmelCase__ = '''glpn''' def __init__(self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[8, 4, 2, 1] , SCREAMING_SNAKE_CASE_=[32, 64, 1_60, 2_56] , SCREAMING_SNAKE_CASE_=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE_=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[1, 2, 5, 8] , SCREAMING_SNAKE_CASE_=[4, 4, 4, 4] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1e-6 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=-1 , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) 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_ = initializer_range SCREAMING_SNAKE_CASE_ = drop_path_rate SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = decoder_hidden_size SCREAMING_SNAKE_CASE_ = max_depth SCREAMING_SNAKE_CASE_ = head_in_index
628
0
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class snake_case ( __a ): @staticmethod @abstractmethod def _lowercase (SCREAMING_SNAKE_CASE_ ): """simple docstring""" raise NotImplementedError() @abstractmethod def _lowercase (self ): """simple docstring""" raise NotImplementedError()
706
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = KandinskyVaaControlnetPipeline UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCAmelCase__ = False @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return self.time_input_dim @property def _lowercase (self ): """simple docstring""" return self.time_input_dim * 4 @property def _lowercase (self ): """simple docstring""" return 1_00 @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE_ = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def _lowercase (self ): """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = VQModel(**self.dummy_movq_kwargs ) return model def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.dummy_unet SCREAMING_SNAKE_CASE_ = self.dummy_movq SCREAMING_SNAKE_CASE_ = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='''linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , steps_offset=1 , prediction_type='''epsilon''' , thresholding=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): """simple docstring""" SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( SCREAMING_SNAKE_CASE_ ) # create hint SCREAMING_SNAKE_CASE_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = { '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 64, '''width''': 64, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''cpu''' SCREAMING_SNAKE_CASE_ = self.get_dummy_components() SCREAMING_SNAKE_CASE_ = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = output.images SCREAMING_SNAKE_CASE_ = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[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.6_95_98_26, 0.86_82_79, 0.7_55_80_92, 0.68_76_94_67, 0.85_80_58_04, 0.65_97_74_96, 0.44_88_53_02, 0.5_95_91_11, 0.4_25_15_95] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy''' ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE_ ) ).float() / 2_55.0 SCREAMING_SNAKE_CASE_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) SCREAMING_SNAKE_CASE_ = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = KandinskyVaaControlnetPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''A robot, 4k photo''' SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = pipe_prior( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipeline( image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , hint=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=1_00 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
628
0
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = r'\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n or scores for each vocabulary token after SoftMax.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional stopping criteria specific kwargs.\n\n Return:\n `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n' class snake_case ( __lowercase ): @add_start_docstrings(__lowerCAmelCase ) def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" raise NotImplementedError('''StoppingCriteria needs to be subclassed''' ) class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = max_length SCREAMING_SNAKE_CASE_ = max_position_embeddings @add_start_docstrings(__lowerCAmelCase ) def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = input_ids.shape[-1] SCREAMING_SNAKE_CASE_ = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( '''This is a friendly reminder - the current text generation call will exceed the model\'s predefined ''' f'maximum length ({self.max_position_embeddings}). Depending on the model, you may observe ' '''exceptions, performance degradation, or nothing at all.''' ) return is_done class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" warnings.warn( '''The class `MaxNewTokensCriteria` is deprecated. ''' f'Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` ' '''with `max_length = start_length + max_new_tokens` instead.''' , __lowerCAmelCase , ) SCREAMING_SNAKE_CASE_ = start_length SCREAMING_SNAKE_CASE_ = max_new_tokens SCREAMING_SNAKE_CASE_ = start_length + max_new_tokens @add_start_docstrings(__lowerCAmelCase ) def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return input_ids.shape[-1] >= self.max_length class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = max_time SCREAMING_SNAKE_CASE_ = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(__lowerCAmelCase ) def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return time.time() - self.initial_timestamp > self.max_time class snake_case ( __lowercase ): @add_start_docstrings(__lowerCAmelCase ) def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return any(criteria(__lowerCAmelCase , __lowerCAmelCase ) for criteria in self ) @property def _lowercase (self ): """simple docstring""" for stopping_criterium in self: if isinstance(__lowerCAmelCase , __lowerCAmelCase ): return stopping_criterium.max_length elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): return stopping_criterium.max_length return None def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = stopping_criteria.max_length SCREAMING_SNAKE_CASE_ = deepcopy(__snake_case ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn('''You set different `max_length` for stopping criteria and `max_length` parameter''', __snake_case ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=__snake_case ) ) return new_stopping_criteria
707
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class snake_case ( __lowercase ): UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_="cls" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = project_dim SCREAMING_SNAKE_CASE_ = pooler_fn SCREAMING_SNAKE_CASE_ = learn_encoder SCREAMING_SNAKE_CASE_ = use_attention_mask class snake_case ( __lowercase ): UpperCAmelCase__ = [R'''pooler''', R'''logit_scale'''] UpperCAmelCase__ = [R'''position_ids''', R'''predictions.decoder.bias'''] UpperCAmelCase__ = '''roberta''' UpperCAmelCase__ = RobertaSeriesConfig def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = XLMRobertaModel(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = getattr(SCREAMING_SNAKE_CASE_ , '''has_pre_transformation''' , SCREAMING_SNAKE_CASE_ ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def _lowercase (self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE_ = self.base_model( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , position_ids=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=SCREAMING_SNAKE_CASE_ , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = outputs['''hidden_states'''][-2] SCREAMING_SNAKE_CASE_ = self.pre_LN(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.transformation_pre(SCREAMING_SNAKE_CASE_ ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE_ = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
628
0
"""simple docstring""" def _lowerCamelCase ( __a ): assert ( isinstance(UpperCAmelCase__, UpperCAmelCase__ ) and number_of_steps > 0 ), F'number_of_steps needs to be positive integer, your input {number_of_steps}' if number_of_steps == 1: return 1 SCREAMING_SNAKE_CASE_ = 1, 1 for _ in range(number_of_steps - 1 ): SCREAMING_SNAKE_CASE_ = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
708
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _lowerCamelCase ( __a, __a=0.9_9_9, __a="cosine", ): if alpha_transform_type == "cosine": def alpha_bar_fn(__a ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__a ): return math.exp(t * -1_2.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) SCREAMING_SNAKE_CASE_ = [] for i in range(__a ): SCREAMING_SNAKE_CASE_ = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__a ) / alpha_bar_fn(__a ), __a ) ) return torch.tensor(__a, dtype=torch.floataa ) class snake_case ( __lowercase , __lowercase ): UpperCAmelCase__ = [e.name for e in KarrasDiffusionSchedulers] UpperCAmelCase__ = 2 @register_to_config def __init__(self , SCREAMING_SNAKE_CASE_ = 10_00 , SCREAMING_SNAKE_CASE_ = 0.0_00_85 , SCREAMING_SNAKE_CASE_ = 0.0_12 , SCREAMING_SNAKE_CASE_ = "linear" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "epsilon" , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = "linspace" , SCREAMING_SNAKE_CASE_ = 0 , ): """simple docstring""" if trained_betas is not None: SCREAMING_SNAKE_CASE_ = torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE_ = torch.linspace(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) SCREAMING_SNAKE_CASE_ = 1.0 - self.betas SCREAMING_SNAKE_CASE_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = use_karras_sigmas def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" if schedule_timesteps is None: SCREAMING_SNAKE_CASE_ = self.timesteps SCREAMING_SNAKE_CASE_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: SCREAMING_SNAKE_CASE_ = 1 if len(SCREAMING_SNAKE_CASE_ ) > 1 else 0 else: SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep SCREAMING_SNAKE_CASE_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self ): """simple docstring""" if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = num_inference_steps SCREAMING_SNAKE_CASE_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": SCREAMING_SNAKE_CASE_ = np.linspace(0 , num_train_timesteps - 1 , SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )[::-1].copy() elif self.config.timestep_spacing == "leading": SCREAMING_SNAKE_CASE_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(0 , SCREAMING_SNAKE_CASE_ ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": SCREAMING_SNAKE_CASE_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(SCREAMING_SNAKE_CASE_ , 0 , -step_ratio )).round().copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps -= 1 else: raise ValueError( f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) SCREAMING_SNAKE_CASE_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.interp(SCREAMING_SNAKE_CASE_ , np.arange(0 , len(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) if self.config.use_karras_sigmas: SCREAMING_SNAKE_CASE_ = self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE_ , num_inference_steps=self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for sigma in sigmas] ) SCREAMING_SNAKE_CASE_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = timesteps.to(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = timesteps.to(device=SCREAMING_SNAKE_CASE_ ) # empty dt and derivative SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter SCREAMING_SNAKE_CASE_ = defaultdict(SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) # get distribution SCREAMING_SNAKE_CASE_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range SCREAMING_SNAKE_CASE_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) SCREAMING_SNAKE_CASE_ = low_idx + 1 SCREAMING_SNAKE_CASE_ = log_sigmas[low_idx] SCREAMING_SNAKE_CASE_ = log_sigmas[high_idx] # interpolate sigmas SCREAMING_SNAKE_CASE_ = (low - log_sigma) / (low - high) SCREAMING_SNAKE_CASE_ = np.clip(SCREAMING_SNAKE_CASE_ , 0 , 1 ) # transform interpolation to time range SCREAMING_SNAKE_CASE_ = (1 - w) * low_idx + w * high_idx SCREAMING_SNAKE_CASE_ = t.reshape(sigma.shape ) return t def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = in_sigmas[-1].item() SCREAMING_SNAKE_CASE_ = in_sigmas[0].item() SCREAMING_SNAKE_CASE_ = 7.0 # 7.0 is the value used in the paper SCREAMING_SNAKE_CASE_ = np.linspace(0 , 1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = sigma_min ** (1 / rho) SCREAMING_SNAKE_CASE_ = sigma_max ** (1 / rho) SCREAMING_SNAKE_CASE_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self ): """simple docstring""" return self.dt is None def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) # advance index counter by 1 SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = self.sigmas[step_index - 1] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE_ = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: SCREAMING_SNAKE_CASE_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep SCREAMING_SNAKE_CASE_ = sigma_next - sigma_hat # store for 2nd order step SCREAMING_SNAKE_CASE_ = derivative SCREAMING_SNAKE_CASE_ = dt SCREAMING_SNAKE_CASE_ = sample else: # 2. 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_next SCREAMING_SNAKE_CASE_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample SCREAMING_SNAKE_CASE_ = self.dt SCREAMING_SNAKE_CASE_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE_ ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = [self.index_for_timestep(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for t in timesteps] SCREAMING_SNAKE_CASE_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): SCREAMING_SNAKE_CASE_ = sigma.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_ = original_samples + noise * sigma return noisy_samples def __len__(self ): """simple docstring""" return self.config.num_train_timesteps
628
0
"""simple docstring""" import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class snake_case ( unittest.TestCase ): def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = jnp.ones((batch_size, length) ) / length return scores def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(batch_size=2 , length=lowerCAmelCase__ ) # tweak scores to not be uniform anymore SCREAMING_SNAKE_CASE_ = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch SCREAMING_SNAKE_CASE_ = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax SCREAMING_SNAKE_CASE_ = jax.nn.softmax(lowerCAmelCase__ , axis=-1 ) SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=1.3 ) SCREAMING_SNAKE_CASE_ = jax.nn.softmax(temp_dist_warper_sharper(lowerCAmelCase__ , scores.copy() , cur_len=lowerCAmelCase__ ) , axis=-1 ) SCREAMING_SNAKE_CASE_ = jax.nn.softmax(temp_dist_warper_smoother(lowerCAmelCase__ , scores.copy() , cur_len=lowerCAmelCase__ ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 2 # create ramp distribution SCREAMING_SNAKE_CASE_ = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() SCREAMING_SNAKE_CASE_ = ramp_logits[1:, : vocab_size // 2] + vocab_size SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case SCREAMING_SNAKE_CASE_ = 5 SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) SCREAMING_SNAKE_CASE_ = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, length) ).copy() SCREAMING_SNAKE_CASE_ = top_k_warp_safety_check(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) SCREAMING_SNAKE_CASE_ = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.8 ) SCREAMING_SNAKE_CASE_ = np.exp(top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 SCREAMING_SNAKE_CASE_ = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # check edge cases with negative and extreme logits SCREAMING_SNAKE_CASE_ = np.broadcast_to(np.arange(lowerCAmelCase__ )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme SCREAMING_SNAKE_CASE_ = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) SCREAMING_SNAKE_CASE_ = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) # check that min length is applied at length 5 SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, 20) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ = 5 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = min_dist_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = 15 SCREAMING_SNAKE_CASE_ = min_dist_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) # check that all scores are -inf except the bos_token_id score SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, 1) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 5 SCREAMING_SNAKE_CASE_ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) # check that all scores are -inf except the eos_token_id when max_length is reached SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, 4) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) self.assertFalse(jnp.isinf(lowerCAmelCase__ ).any() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 15 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, sequence_length) , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = input_ids.copy() SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = 10 # no processor list SCREAMING_SNAKE_CASE_ = temp_dist_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = min_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = bos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = eos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # with processor list SCREAMING_SNAKE_CASE_ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE_ = processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 15 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, sequence_length) , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = input_ids.copy() SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = 10 # no processor list def run_no_processor_list(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = temp_dist_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = top_k_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = top_p_warp(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = min_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = bos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = eos_dist_proc(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) return scores # with processor list def run_processor_list(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE_ = processor(lowerCAmelCase__ , lowerCAmelCase__ , cur_len=lowerCAmelCase__ ) return scores SCREAMING_SNAKE_CASE_ = jax.jit(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = jax.jit(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = jitted_run_no_processor_list(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = jitted_run_processor_list(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
709
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = 8 # DPR tok SCREAMING_SNAKE_CASE_ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , DPR_VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) # BART tok SCREAMING_SNAKE_CASE_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE_ = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''bart_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self ): """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''bart_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''custom''' , ) if from_disk: SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dataset''' ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''index.faiss''' ) dataset.get_index('''embeddings''' ).save(os.path.join(self.tmpdirname , '''index.faiss''' ) ) dataset.drop_index('''embeddings''' ) dataset.save_to_disk(os.path.join(self.tmpdirname , '''dataset''' ) ) del dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , SCREAMING_SNAKE_CASE_ ) , ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''hf_bert_base.hnswSQ8_correct_phi_128.c_index''' ) dataset.save_faiss_index('''embeddings''' , index_file_name + '''.index.dpr''' ) pickle.dump(dataset['''id'''] , open(index_file_name + '''.index_meta.dpr''' , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''psgs_w100.tsv.pkl''' ) SCREAMING_SNAKE_CASE_ = {sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset} pickle.dump(SCREAMING_SNAKE_CASE_ , open(SCREAMING_SNAKE_CASE_ , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''legacy''' , index_path=self.tmpdirname , ) SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''text'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''text'''][0] , '''bar''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''text'''][0] , '''foo''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) SCREAMING_SNAKE_CASE_ = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( # noqa: F841 out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], out['''doc_ids'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dpr_ctx_encoder_tokenizer() SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) retriever.set_ctx_encoder_tokenizer(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual( len(SCREAMING_SNAKE_CASE_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''') ) , SCREAMING_SNAKE_CASE_ ) # check for doc token related keys in dictionary.
628
0
"""simple docstring""" lowerCAmelCase__ = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def _lowerCamelCase ( __a ): if not isinstance(UpperCAmelCase__, UpperCAmelCase__ ): SCREAMING_SNAKE_CASE_ = F'a bytes-like object is required, not \'{data.__class__.__name__}\'' raise TypeError(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE_ = ''''''.join(bin(UpperCAmelCase__ )[2:].zfill(8 ) for byte in data ) SCREAMING_SNAKE_CASE_ = len(UpperCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later SCREAMING_SNAKE_CASE_ = B'''=''' * ((6 - len(UpperCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(UpperCAmelCase__ ) % 6) else: SCREAMING_SNAKE_CASE_ = B'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6], 2 )] for index in range(0, len(UpperCAmelCase__ ), 6 ) ).encode() + padding ) def _lowerCamelCase ( __a ): if not isinstance(UpperCAmelCase__, UpperCAmelCase__ ) and not isinstance(UpperCAmelCase__, UpperCAmelCase__ ): SCREAMING_SNAKE_CASE_ = ( '''argument should be a bytes-like object or ASCII string, ''' F'not \'{encoded_data.__class__.__name__}\'' ) raise TypeError(UpperCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(UpperCAmelCase__, UpperCAmelCase__ ): try: SCREAMING_SNAKE_CASE_ = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) SCREAMING_SNAKE_CASE_ = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(UpperCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one SCREAMING_SNAKE_CASE_ = encoded_data[:-padding] SCREAMING_SNAKE_CASE_ = ''''''.join( bin(B64_CHARSET.index(UpperCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: SCREAMING_SNAKE_CASE_ = ''''''.join( bin(B64_CHARSET.index(UpperCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) SCREAMING_SNAKE_CASE_ = [ int(binary_stream[index : index + 8], 2 ) for index in range(0, len(UpperCAmelCase__ ), 8 ) ] return bytes(UpperCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
710
"""simple docstring""" from collections.abc import Sequence from queue import Queue class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = start SCREAMING_SNAKE_CASE_ = end SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = left SCREAMING_SNAKE_CASE_ = right def __repr__(self ): """simple docstring""" return f'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = collection SCREAMING_SNAKE_CASE_ = function if self.collection: SCREAMING_SNAKE_CASE_ = self._build_tree(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self._update_tree(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self._query_range(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.collection[start] ) SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = self._build_tree(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE_ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == i: SCREAMING_SNAKE_CASE_ = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.fn(node.left.val , node.right.val ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE_ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE_ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" if self.root is not None: SCREAMING_SNAKE_CASE_ = Queue() queue.put(self.root ) while not queue.empty(): SCREAMING_SNAKE_CASE_ = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('*' * 50) lowerCAmelCase__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
628
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
711
"""simple docstring""" def _lowerCamelCase ( __a ): if not isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be an integer' raise TypeError(__a ) if number < 1: SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be > 0' raise ValueError(__a ) SCREAMING_SNAKE_CASE_ = 1 for i in range(1, __a ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
628
0
"""simple docstring""" import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE_ = FlaxDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-pipe''' , safety_checker=UpperCamelCase__ , cache_dir=UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = [t[-1] for t in os.walk(os.path.join(UpperCamelCase__ , os.listdir(UpperCamelCase__ )[0] , '''snapshots''' ) )] SCREAMING_SNAKE_CASE_ = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('''.bin''' ) for f in files ) @slow @require_flax class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-pipe''' , safety_checker=UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) SCREAMING_SNAKE_CASE_ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = jax.device_count() SCREAMING_SNAKE_CASE_ = num_samples * [prompt] SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(UpperCamelCase__ ) # shard inputs and rng SCREAMING_SNAKE_CASE_ = replicate(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = jax.random.split(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = shard(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , jit=UpperCamelCase__ ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1_51_47_45 ) < 1e-3 assert np.abs(np.abs(UpperCamelCase__ , dtype=np.floataa ).sum() - 4_99_47.8_75 ) < 5e-1 SCREAMING_SNAKE_CASE_ = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(UpperCamelCase__ ) == num_samples def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''flax''' , safety_checker=UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) SCREAMING_SNAKE_CASE_ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_ = 50 SCREAMING_SNAKE_CASE_ = jax.device_count() SCREAMING_SNAKE_CASE_ = num_samples * [prompt] SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(UpperCamelCase__ ) # shard inputs and rng SCREAMING_SNAKE_CASE_ = replicate(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = jax.random.split(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = shard(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , jit=UpperCamelCase__ ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05_65_24_01) ) < 1e-3 assert np.abs((np.abs(UpperCamelCase__ , dtype=np.floataa ).sum() - 2_38_38_08.2) ) < 5e-1 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) SCREAMING_SNAKE_CASE_ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_ = 50 SCREAMING_SNAKE_CASE_ = jax.device_count() SCREAMING_SNAKE_CASE_ = num_samples * [prompt] SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(UpperCamelCase__ ) # shard inputs and rng SCREAMING_SNAKE_CASE_ = replicate(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = jax.random.split(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = shard(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , jit=UpperCamelCase__ ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1e-3 assert np.abs((np.abs(UpperCamelCase__ , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5e-1 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa ) SCREAMING_SNAKE_CASE_ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) SCREAMING_SNAKE_CASE_ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_ = 50 SCREAMING_SNAKE_CASE_ = jax.device_count() SCREAMING_SNAKE_CASE_ = num_samples * [prompt] SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(UpperCamelCase__ ) # shard inputs and rng SCREAMING_SNAKE_CASE_ = replicate(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = jax.random.split(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = shard(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , jit=UpperCamelCase__ ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1e-3 assert np.abs((np.abs(UpperCamelCase__ , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5e-1 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , set_alpha_to_one=UpperCamelCase__ , steps_offset=1 , ) SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , scheduler=UpperCamelCase__ , safety_checker=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE_ = scheduler.create_state() SCREAMING_SNAKE_CASE_ = scheduler_state SCREAMING_SNAKE_CASE_ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) SCREAMING_SNAKE_CASE_ = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE_ = 50 SCREAMING_SNAKE_CASE_ = jax.device_count() SCREAMING_SNAKE_CASE_ = num_samples * [prompt] SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(UpperCamelCase__ ) # shard inputs and rng SCREAMING_SNAKE_CASE_ = replicate(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = jax.random.split(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = shard(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , jit=UpperCamelCase__ ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_45_04_39_45) ) < 1e-3 assert np.abs((np.abs(UpperCamelCase__ , dtype=np.floataa ).sum() - 2_34_76_93.5) ) < 5e-1 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) SCREAMING_SNAKE_CASE_ = jax.device_count() SCREAMING_SNAKE_CASE_ = num_samples * [prompt] SCREAMING_SNAKE_CASE_ = jax.random.split(jax.random.PRNGKey(0 ) , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE_ = replicate(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = shard(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , jit=UpperCamelCase__ ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = images[2, 0, 2_56, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase__ , use_memory_efficient_attention=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE_ = replicate(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = shard(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = pipeline(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , jit=UpperCamelCase__ ).images assert images_eff.shape == (num_samples, 1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = images[2, 0, 2_56, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1e-2
712
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = len(__a ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: SCREAMING_SNAKE_CASE_ = i + 1 else: SCREAMING_SNAKE_CASE_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f'''{two_pointer([2, 7, 11, 15], 9) = }''')
628
0
"""simple docstring""" from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = parent SCREAMING_SNAKE_CASE_ = batch_size SCREAMING_SNAKE_CASE_ = image_size SCREAMING_SNAKE_CASE_ = patch_size SCREAMING_SNAKE_CASE_ = num_channels SCREAMING_SNAKE_CASE_ = is_training SCREAMING_SNAKE_CASE_ = use_labels SCREAMING_SNAKE_CASE_ = hidden_size SCREAMING_SNAKE_CASE_ = num_hidden_layers SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = intermediate_size SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = hidden_dropout_prob SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ = type_sequence_label_size SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = scope SCREAMING_SNAKE_CASE_ = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE_ = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE_ = num_patches + 2 def _lowercase (self ): """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.type_sequence_label_size ) SCREAMING_SNAKE_CASE_ = self.get_config() return config, pixel_values, labels def _lowercase (self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFDeiTModel(config=_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFDeiTForMaskedImageModeling(config=_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = TFDeiTForMaskedImageModeling(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.type_sequence_label_size SCREAMING_SNAKE_CASE_ = TFDeiTForImageClassification(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = TFDeiTForImageClassification(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = config_and_inputs SCREAMING_SNAKE_CASE_ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class snake_case ( __lowercase , __lowercase , unittest.TestCase ): UpperCAmelCase__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) UpperCAmelCase__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFDeiTModelTester(self ) SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _lowercase (self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """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(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) SCREAMING_SNAKE_CASE_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , tf.keras.layers.Dense ) ) def _lowercase (self ): """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(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = inspect.signature(model.call ) # 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] , _SCREAMING_SNAKE_CASE ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_SCREAMING_SNAKE_CASE ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): """simple docstring""" SCREAMING_SNAKE_CASE_ = super()._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def _lowercase (self ): """simple docstring""" for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ = TFDeiTModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def _lowercase (self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) SCREAMING_SNAKE_CASE_ = self.default_image_processor SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors='''tf''' ) # forward pass SCREAMING_SNAKE_CASE_ = model(**_SCREAMING_SNAKE_CASE ) # verify the logits SCREAMING_SNAKE_CASE_ = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
713
"""simple docstring""" import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a=2, __a=3, __a=16, __a = 10, __a = 2 ): def get_dataset(__a ): SCREAMING_SNAKE_CASE_ = torch.randn(batch_size * n_batches, 1 ) return TensorDataset(__a, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1 ) ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) return (train_dataloader, valid_dataloader) def _lowerCamelCase ( __a, __a, __a, __a, __a, __a=None ): SCREAMING_SNAKE_CASE_ = [] for epoch in range(__a ): # Train quickly model.train() for batch in dataloader: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = batch SCREAMING_SNAKE_CASE_ = model(__a ) SCREAMING_SNAKE_CASE_ = torch.nn.functional.mse_loss(__a, __a ) accelerator.backward(__a ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class snake_case ( nn.Module ): def __init__(self ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return x * self.a + self.b class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(total_limit=1 , project_dir=SCREAMING_SNAKE_CASE_ , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''initial''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoint''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) # Load everything back in and make sure all states work accelerator.load_state(SCREAMING_SNAKE_CASE_ ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_1''' ) ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch.tensor([1, 2, 3] ) SCREAMING_SNAKE_CASE_ = torch.tensor([2, 3, 4] ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(net.parameters() ) SCREAMING_SNAKE_CASE_ = Accelerator() with self.assertRaises(SCREAMING_SNAKE_CASE_ ) as ve: accelerator.register_for_checkpointing(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = str(ve.exception ) self.assertTrue('''Item at index 0''' in message ) self.assertTrue('''Item at index 1''' in message ) self.assertFalse('''Item at index 2''' in message ) self.assertFalse('''Item at index 3''' in message ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ = torch.optim.lr_scheduler.StepLR(SCREAMING_SNAKE_CASE_ , step_size=1 , gamma=0.99 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() SCREAMING_SNAKE_CASE_ = scheduler.state_dict() train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) self.assertEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ , total_limit=2 ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_9''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_10''' ) ) ) @require_cuda def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() ) if __name__ == "__main__": lowerCAmelCase__ = '/tmp/accelerate/state_checkpointing' lowerCAmelCase__ = DummyModel() lowerCAmelCase__ = torch.optim.Adam(params=model.parameters(), lr=1e-3) lowerCAmelCase__ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) lowerCAmelCase__, lowerCAmelCase__ = dummy_dataloaders() lowerCAmelCase__ = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline lowerCAmelCase__ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert param_device.type == accelerator.device.type lowerCAmelCase__ = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
628
0
"""simple docstring""" import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class snake_case : @staticmethod def _lowercase (*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" pass @is_pipeline_test @require_vision @require_torch class snake_case ( unittest.TestCase ): UpperCAmelCase__ = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = pipeline( '''zero-shot-object-detection''' , model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) SCREAMING_SNAKE_CASE_ = [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] return object_detector, examples def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = object_detector(examples[0] , threshold=0.0 ) SCREAMING_SNAKE_CASE_ = len(SCREAMING_SNAKE_CASE_ ) self.assertGreater(SCREAMING_SNAKE_CASE_ , 0 ) self.assertEqual( SCREAMING_SNAKE_CASE_ , [ { '''score''': ANY(SCREAMING_SNAKE_CASE_ ), '''label''': ANY(SCREAMING_SNAKE_CASE_ ), '''box''': {'''xmin''': ANY(SCREAMING_SNAKE_CASE_ ), '''ymin''': ANY(SCREAMING_SNAKE_CASE_ ), '''xmax''': ANY(SCREAMING_SNAKE_CASE_ ), '''ymax''': ANY(SCREAMING_SNAKE_CASE_ )}, } for i in range(SCREAMING_SNAKE_CASE_ ) ] , ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def _lowercase (self ): """simple docstring""" pass @require_torch def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = pipeline( '''zero-shot-object-detection''' , model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) SCREAMING_SNAKE_CASE_ = object_detector( '''./tests/fixtures/tests_samples/COCO/000000039769.png''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , threshold=0.64 , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 2_74, '''xmax''': 93, '''ymax''': 2_97}}, {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, ] , ) SCREAMING_SNAKE_CASE_ = object_detector( [ { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ [ {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 2_74, '''xmax''': 93, '''ymax''': 2_97}}, {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, ] ] , ) @require_torch @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = pipeline('''zero-shot-object-detection''' ) SCREAMING_SNAKE_CASE_ = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}}, {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}}, ] , ) SCREAMING_SNAKE_CASE_ = object_detector( [ { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, ] , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ [ {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}}, {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}}, ], [ {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}}, {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}}, ], ] , ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def _lowercase (self ): """simple docstring""" pass @require_torch @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 0.2 SCREAMING_SNAKE_CASE_ = pipeline('''zero-shot-object-detection''' ) SCREAMING_SNAKE_CASE_ = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , threshold=SCREAMING_SNAKE_CASE_ , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, ] , ) @require_torch @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = pipeline('''zero-shot-object-detection''' ) SCREAMING_SNAKE_CASE_ = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , top_k=SCREAMING_SNAKE_CASE_ , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [ {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, ] , )
714
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class snake_case ( __lowercase ): UpperCAmelCase__ = (DDIMParallelScheduler,) UpperCAmelCase__ = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def _lowercase (self ): """simple docstring""" for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def _lowercase (self ): """simple docstring""" for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , sample_max_value=SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.1_47_71 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.3_24_60 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = 10, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE_ = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 11_47.79_04 ) < 1e-2 assert abs(result_mean.item() - 0.49_82 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop() SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_72.00_67 ) < 1e-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 52.53_02 ) < 1e-2 assert abs(result_mean.item() - 0.06_84 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.82_95 ) < 1e-2 assert abs(result_mean.item() - 0.19_51 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.07_84 ) < 1e-2 assert abs(result_mean.item() - 0.19_41 ) < 1e-3
628
0
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] SCREAMING_SNAKE_CASE_ = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE_ = [4, 4, 4, 4] SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE_ = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE_ = 128 elif "large" in model_name: SCREAMING_SNAKE_CASE_ = 192 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE_ = 256 elif "huge" in model_name: SCREAMING_SNAKE_CASE_ = 352 # set label information SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE_ = '''imagenet-22k-id2label.json''' else: SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = FocalNetConfig( embed_dim=SCREAMING_SNAKE_CASE_, depths=SCREAMING_SNAKE_CASE_, focal_levels=SCREAMING_SNAKE_CASE_, focal_windows=SCREAMING_SNAKE_CASE_, use_conv_embed=SCREAMING_SNAKE_CASE_, idalabel=SCREAMING_SNAKE_CASE_, labelaid=SCREAMING_SNAKE_CASE_, use_post_layernorm=SCREAMING_SNAKE_CASE_, use_layerscale=SCREAMING_SNAKE_CASE_, ) return config def _lowerCamelCase ( __a ): 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 "layers" in name: SCREAMING_SNAKE_CASE_ = '''encoder.''' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE_ = name.replace('''encoder.layers''', '''encoder.stages''' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('''downsample.proj''', '''downsample.projection''' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ = name.replace('''blocks''', '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.f''', '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.h''', '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.proj''', '''modulation.projection_out''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE_ = '''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE_ = '''layernorm.bias''' if "head" in name: SCREAMING_SNAKE_CASE_ = name.replace('''head''', '''classifier''' ) else: SCREAMING_SNAKE_CASE_ = '''focalnet.''' + name return name def _lowerCamelCase ( __a, __a, __a=False ): # fmt: off SCREAMING_SNAKE_CASE_ = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on SCREAMING_SNAKE_CASE_ = model_name_to_url[model_name] print('''Checkpoint URL: ''', SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_, map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = state_dict.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = get_focalnet_config(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = FocalNetForImageClassification(SCREAMING_SNAKE_CASE_ ) model.eval() # load state dict model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # verify conversion SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = BitImageProcessor( do_resize=SCREAMING_SNAKE_CASE_, size={'''shortest_edge''': 256}, resample=PILImageResampling.BILINEAR, do_center_crop=SCREAMING_SNAKE_CASE_, crop_size=224, do_normalize=SCREAMING_SNAKE_CASE_, image_mean=SCREAMING_SNAKE_CASE_, image_std=SCREAMING_SNAKE_CASE_, ) SCREAMING_SNAKE_CASE_ = Image.open(requests.get(SCREAMING_SNAKE_CASE_, stream=SCREAMING_SNAKE_CASE_ ).raw ) SCREAMING_SNAKE_CASE_ = processor(images=SCREAMING_SNAKE_CASE_, return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE_ = image_transforms(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values, SCREAMING_SNAKE_CASE_, atol=1E-4 ) SCREAMING_SNAKE_CASE_ = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(-1 ).item() print('''Predicted class:''', model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''', outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE_ = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE_ = torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8] ) assert torch.allclose(outputs.logits[0, :3], SCREAMING_SNAKE_CASE_, atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model and processor of {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: print(F'Pushing model and processor of {model_name} to the hub...' ) model.push_to_hub(F'{model_name}' ) processor.push_to_hub(F'{model_name}' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
715
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = TransfoXLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''<unk> UNwanted , running''' SCREAMING_SNAKE_CASE_ = '''<unk> unwanted, running''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [0, 4, 8, 7] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' SCREAMING_SNAKE_CASE_ = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = len(SCREAMING_SNAKE_CASE_ ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
628
0
"""simple docstring""" from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class snake_case ( __snake_case ): def __lt__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self[-1] < other[-1] def __eq__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self[-1] == other[-1] def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [] # sort into stacks for element in collection: SCREAMING_SNAKE_CASE_ = Stack([element] ) SCREAMING_SNAKE_CASE_ = bisect_left(_lowerCAmelCase, _lowerCAmelCase ) if i != len(_lowerCAmelCase ): stacks[i].append(_lowerCAmelCase ) else: stacks.append(_lowerCAmelCase ) # use a heap-based merge to merge stack efficiently SCREAMING_SNAKE_CASE_ = merge(*(reversed(_lowerCAmelCase ) for stack in stacks) ) return collection if __name__ == "__main__": lowerCAmelCase__ = input('Enter numbers separated by a comma:\n').strip() lowerCAmelCase__ = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
716
"""simple docstring""" from __future__ import annotations import typing from collections import Counter def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__a, max_perimeter + 1 ): SCREAMING_SNAKE_CASE_ = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__a ): SCREAMING_SNAKE_CASE_ = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _lowerCamelCase ( __a = 1_000 ): SCREAMING_SNAKE_CASE_ = pythagorean_triple(__a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
628
0
"""simple docstring""" from __future__ import annotations from collections import deque class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] self.adlist.append( {'''value''': '''''', '''next_states''': [], '''fail_state''': 0, '''output''': []} ) for keyword in keywords: self.add_keyword(SCREAMING_SNAKE_CASE_ ) self.set_fail_transitions() def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 0 for character in keyword: SCREAMING_SNAKE_CASE_ = self.find_next_state(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if next_state is None: self.adlist.append( { '''value''': character, '''next_states''': [], '''fail_state''': 0, '''output''': [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) SCREAMING_SNAKE_CASE_ = len(self.adlist ) - 1 else: SCREAMING_SNAKE_CASE_ = next_state self.adlist[current_state]["output"].append(SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = deque() for node in self.adlist[0]["next_states"]: q.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = 0 while q: SCREAMING_SNAKE_CASE_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.adlist[r]['''fail_state'''] while ( self.find_next_state(SCREAMING_SNAKE_CASE_ , self.adlist[child]['''value'''] ) is None and state != 0 ): SCREAMING_SNAKE_CASE_ = self.adlist[state]['''fail_state'''] SCREAMING_SNAKE_CASE_ = self.find_next_state( SCREAMING_SNAKE_CASE_ , self.adlist[child]['''value'''] ) if self.adlist[child]["fail_state"] is None: SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = ( self.adlist[child]['''output'''] + self.adlist[self.adlist[child]['''fail_state''']]['''output'''] ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {} # returns a dict with keywords and list of its occurrences SCREAMING_SNAKE_CASE_ = 0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): while ( self.find_next_state(SCREAMING_SNAKE_CASE_ , string[i] ) is None and current_state != 0 ): SCREAMING_SNAKE_CASE_ = self.adlist[current_state]['''fail_state'''] SCREAMING_SNAKE_CASE_ = self.find_next_state(SCREAMING_SNAKE_CASE_ , string[i] ) if next_state is None: SCREAMING_SNAKE_CASE_ = 0 else: SCREAMING_SNAKE_CASE_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: SCREAMING_SNAKE_CASE_ = [] result[key].append(i - len(SCREAMING_SNAKE_CASE_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
717
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _lowerCamelCase ( __a ): if is_torch_version('''<''', '''2.0.0''' ) or not hasattr(__a, '''_dynamo''' ): return False return isinstance(__a, torch._dynamo.eval_frame.OptimizedModule ) def _lowerCamelCase ( __a, __a = True ): SCREAMING_SNAKE_CASE_ = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE_ = is_compiled_module(__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE_ = getattr(__a, '''forward''' ) SCREAMING_SNAKE_CASE_ = model.__dict__.pop('''_original_forward''', __a ) if original_forward is not None: while hasattr(__a, '''__wrapped__''' ): SCREAMING_SNAKE_CASE_ = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE_ = forward if getattr(__a, '''_converted_to_transformer_engine''', __a ): convert_model(__a, to_transformer_engine=__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = compiled_model return model def _lowerCamelCase ( ): PartialState().wait_for_everyone() def _lowerCamelCase ( __a, __a ): if PartialState().distributed_type == DistributedType.TPU: xm.save(__a, __a ) elif PartialState().local_process_index == 0: torch.save(__a, __a ) @contextmanager def _lowerCamelCase ( **__a ): for key, value in kwargs.items(): SCREAMING_SNAKE_CASE_ = str(__a ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _lowerCamelCase ( __a ): if not hasattr(__a, '''__qualname__''' ) and not hasattr(__a, '''__name__''' ): SCREAMING_SNAKE_CASE_ = getattr(__a, '''__class__''', __a ) if hasattr(__a, '''__qualname__''' ): return obj.__qualname__ if hasattr(__a, '''__name__''' ): return obj.__name__ return str(__a ) def _lowerCamelCase ( __a, __a ): for key, value in source.items(): if isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = destination.setdefault(__a, {} ) merge_dicts(__a, __a ) else: SCREAMING_SNAKE_CASE_ = value return destination def _lowerCamelCase ( __a = None ): if port is None: SCREAMING_SNAKE_CASE_ = 29_500 with socket.socket(socket.AF_INET, socket.SOCK_STREAM ) as s: return s.connect_ex(('''localhost''', port) ) == 0
628
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBlipQFormerConfig', 'InstructBlipVisionConfig', ], 'processing_instructblip': ['InstructBlipProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ 'INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'InstructBlipQFormerModel', 'InstructBlipPreTrainedModel', 'InstructBlipForConditionalGeneration', 'InstructBlipVisionModel', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
718
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = CTRLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE_ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
628
0
"""simple docstring""" import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowerCAmelCase__ = False lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = 'ybelkada/fonts' def _lowerCamelCase ( ): if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ' '''Pix2StructImageProcessor. Please upgrade torch.''' ) def _lowerCamelCase ( __a, __a, __a ): requires_backends(lowercase__, ['''torch'''] ) _check_torch_version() SCREAMING_SNAKE_CASE_ = image_tensor.unsqueeze(0 ) SCREAMING_SNAKE_CASE_ = torch.nn.functional.unfold(lowercase__, (patch_height, patch_width), stride=(patch_height, patch_width) ) SCREAMING_SNAKE_CASE_ = patches.reshape(image_tensor.size(0 ), image_tensor.size(1 ), lowercase__, lowercase__, -1 ) SCREAMING_SNAKE_CASE_ = patches.permute(0, 4, 2, 3, 1 ).reshape( image_tensor.size(2 ) // patch_height, image_tensor.size(3 ) // patch_width, image_tensor.size(1 ) * patch_height * patch_width, ) return patches.unsqueeze(0 ) def _lowerCamelCase ( __a, __a = 36, __a = "black", __a = "white", __a = 5, __a = 5, __a = 5, __a = 5, __a = None, __a = None, ): requires_backends(lowercase__, '''vision''' ) # Add new lines so that each line is no more than 80 characters. SCREAMING_SNAKE_CASE_ = textwrap.TextWrapper(width=80 ) SCREAMING_SNAKE_CASE_ = wrapper.wrap(text=lowercase__ ) SCREAMING_SNAKE_CASE_ = '''\n'''.join(lowercase__ ) if font_bytes is not None and font_path is None: SCREAMING_SNAKE_CASE_ = io.BytesIO(lowercase__ ) elif font_path is not None: SCREAMING_SNAKE_CASE_ = font_path else: SCREAMING_SNAKE_CASE_ = hf_hub_download(lowercase__, '''Arial.TTF''' ) SCREAMING_SNAKE_CASE_ = ImageFont.truetype(lowercase__, encoding='''UTF-8''', size=lowercase__ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. SCREAMING_SNAKE_CASE_ = ImageDraw.Draw(Image.new('''RGB''', (1, 1), lowercase__ ) ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = temp_draw.textbbox((0, 0), lowercase__, lowercase__ ) # Create the actual image with a bit of padding around the text. SCREAMING_SNAKE_CASE_ = text_width + left_padding + right_padding SCREAMING_SNAKE_CASE_ = text_height + top_padding + bottom_padding SCREAMING_SNAKE_CASE_ = Image.new('''RGB''', (image_width, image_height), lowercase__ ) SCREAMING_SNAKE_CASE_ = ImageDraw.Draw(lowercase__ ) draw.text(xy=(left_padding, top_padding), text=lowercase__, fill=lowercase__, font=lowercase__ ) return image def _lowerCamelCase ( __a, __a, **__a ): requires_backends(lowercase__, '''vision''' ) # Convert to PIL image if necessary SCREAMING_SNAKE_CASE_ = to_pil_image(lowercase__ ) SCREAMING_SNAKE_CASE_ = render_text(lowercase__, **lowercase__ ) SCREAMING_SNAKE_CASE_ = max(header_image.width, image.width ) SCREAMING_SNAKE_CASE_ = int(image.height * (new_width / image.width) ) SCREAMING_SNAKE_CASE_ = int(header_image.height * (new_width / header_image.width) ) SCREAMING_SNAKE_CASE_ = Image.new('''RGB''', (new_width, new_height + new_header_height), '''white''' ) new_image.paste(header_image.resize((new_width, new_header_height) ), (0, 0) ) new_image.paste(image.resize((new_width, new_height) ), (0, new_header_height) ) # Convert back to the original framework if necessary SCREAMING_SNAKE_CASE_ = to_numpy_array(lowercase__ ) if infer_channel_dimension_format(lowercase__ ) == ChannelDimension.LAST: SCREAMING_SNAKE_CASE_ = to_channel_dimension_format(lowercase__, ChannelDimension.LAST ) return new_image class snake_case ( __a ): UpperCAmelCase__ = ["flattened_patches"] def __init__(self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 20_48 , SCREAMING_SNAKE_CASE_ = False , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(**lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} SCREAMING_SNAKE_CASE_ = do_normalize SCREAMING_SNAKE_CASE_ = do_convert_rgb SCREAMING_SNAKE_CASE_ = max_patches SCREAMING_SNAKE_CASE_ = is_vqa def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" requires_backends(self.extract_flattened_patches , '''torch''' ) _check_torch_version() # convert to torch SCREAMING_SNAKE_CASE_ = to_channel_dimension_format(lowerCAmelCase_ , ChannelDimension.FIRST ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = patch_size['''height'''], patch_size['''width'''] SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = get_image_size(lowerCAmelCase_ ) # maximize scale s.t. SCREAMING_SNAKE_CASE_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) SCREAMING_SNAKE_CASE_ = max(min(math.floor(scale * image_height / patch_height ) , lowerCAmelCase_ ) , 1 ) SCREAMING_SNAKE_CASE_ = max(min(math.floor(scale * image_width / patch_width ) , lowerCAmelCase_ ) , 1 ) SCREAMING_SNAKE_CASE_ = max(num_feasible_rows * patch_height , 1 ) SCREAMING_SNAKE_CASE_ = max(num_feasible_cols * patch_width , 1 ) SCREAMING_SNAKE_CASE_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode='''bilinear''' , align_corners=lowerCAmelCase_ , antialias=lowerCAmelCase_ , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE_ = torch_extract_patches(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = patches.shape SCREAMING_SNAKE_CASE_ = patches_shape[1] SCREAMING_SNAKE_CASE_ = patches_shape[2] SCREAMING_SNAKE_CASE_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] SCREAMING_SNAKE_CASE_ = torch.arange(lowerCAmelCase_ ).reshape([rows, 1] ).repeat(1 , lowerCAmelCase_ ).reshape([rows * columns, 1] ) SCREAMING_SNAKE_CASE_ = torch.arange(lowerCAmelCase_ ).reshape([1, columns] ).repeat(lowerCAmelCase_ , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] SCREAMING_SNAKE_CASE_ = row_ids.to(torch.floataa ) SCREAMING_SNAKE_CASE_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] SCREAMING_SNAKE_CASE_ = torch.nn.functional.pad(lowerCAmelCase_ , [0, 0, 0, max_patches - (rows * columns)] ).float() SCREAMING_SNAKE_CASE_ = to_numpy_array(lowerCAmelCase_ ) return result def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" if image.dtype == np.uinta: SCREAMING_SNAKE_CASE_ = image.astype(np.floataa ) # take mean across the whole `image` SCREAMING_SNAKE_CASE_ = np.mean(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = np.std(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = max(lowerCAmelCase_ , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(lowerCAmelCase_ , mean=lowerCAmelCase_ , std=lowerCAmelCase_ , **lowerCAmelCase_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb SCREAMING_SNAKE_CASE_ = patch_size if patch_size is not None else self.patch_size SCREAMING_SNAKE_CASE_ = max_patches if max_patches is not None else self.max_patches SCREAMING_SNAKE_CASE_ = self.is_vqa if kwargs.get('''data_format''' , lowerCAmelCase_ ) is not None: raise ValueError('''data_format is not an accepted input as the outputs are ''' ) SCREAMING_SNAKE_CASE_ = make_list_of_images(lowerCAmelCase_ ) if not valid_images(lowerCAmelCase_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: SCREAMING_SNAKE_CASE_ = [convert_to_rgb(lowerCAmelCase_ ) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ = [to_numpy_array(lowerCAmelCase_ ) for image in images] if is_vqa: if header_text is None: raise ValueError('''A header text must be provided for VQA models.''' ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''font_bytes''' , lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = kwargs.pop('''font_path''' , lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): SCREAMING_SNAKE_CASE_ = [header_text] * len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = [ render_header(lowerCAmelCase_ , header_text[i] , font_bytes=lowerCAmelCase_ , font_path=lowerCAmelCase_ ) for i, image in enumerate(lowerCAmelCase_ ) ] if do_normalize: SCREAMING_SNAKE_CASE_ = [self.normalize(image=lowerCAmelCase_ ) for image in images] # convert to torch tensor and permute SCREAMING_SNAKE_CASE_ = [ self.extract_flattened_patches(image=lowerCAmelCase_ , max_patches=lowerCAmelCase_ , patch_size=lowerCAmelCase_ ) for image in images ] # create attention mask in numpy SCREAMING_SNAKE_CASE_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] SCREAMING_SNAKE_CASE_ = BatchFeature( data={'''flattened_patches''': images, '''attention_mask''': attention_masks} , tensor_type=lowerCAmelCase_ ) return encoded_outputs
719
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a, __a ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_ = BigBirdConfig.from_json_file(__a ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: SCREAMING_SNAKE_CASE_ = BigBirdForQuestionAnswering(__a ) else: SCREAMING_SNAKE_CASE_ = BigBirdForPreTraining(__a ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__a, __a, is_trivia_qa=__a ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) 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( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
628
0
"""simple docstring""" 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 _lowerCamelCase ( ): 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 _lowerCamelCase ( __a=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 _lowerCamelCase ( __a ): 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 _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = config_command_parser() SCREAMING_SNAKE_CASE_ = parser.parse_args() config_command(UpperCamelCase__ ) if __name__ == "__main__": main()
720
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name def _lowerCamelCase ( __a ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''', __a, ) if isinstance(__a, torch.Tensor ): return image elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [image] if isinstance(image[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = image[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE_ = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = np.array(__a ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = image.transpose(0, 3, 1, 2 ) SCREAMING_SNAKE_CASE_ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(image[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return image def _lowerCamelCase ( __a ): if isinstance(__a, torch.Tensor ): return mask elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [mask] if isinstance(mask[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = mask[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE_ = [np.array(m.convert('''L''' ).resize((w, h), resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(mask[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return mask class snake_case ( __lowercase ): UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 2_50 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = image SCREAMING_SNAKE_CASE_ = _preprocess_image(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = _preprocess_mask(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE_ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) SCREAMING_SNAKE_CASE_ = original_image.shape SCREAMING_SNAKE_CASE_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) SCREAMING_SNAKE_CASE_ = eta SCREAMING_SNAKE_CASE_ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE_ = generator[0] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE_ = self.scheduler.undo_step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = t SCREAMING_SNAKE_CASE_ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
628
0
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = MobileNetVaConfig(layer_norm_eps=0.0_0_1 ) if "_quant" in model_name: raise ValueError('''Quantized models are not supported.''' ) SCREAMING_SNAKE_CASE_ = re.match(r'''^mobilenet_v1_([^_]*)_([^_]*)$''', _UpperCamelCase ) if matches: SCREAMING_SNAKE_CASE_ = float(matches[1] ) SCREAMING_SNAKE_CASE_ = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". SCREAMING_SNAKE_CASE_ = 1_001 SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_UpperCamelCase, _UpperCamelCase, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(_UpperCamelCase ) + 1: v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = '''background''' SCREAMING_SNAKE_CASE_ = idalabel SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} return config def _lowerCamelCase ( ): 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 _lowerCamelCase ( __a, __a, __a, __a=False ): SCREAMING_SNAKE_CASE_ = get_mobilenet_va_config(_UpperCamelCase ) # Load 🤗 model SCREAMING_SNAKE_CASE_ = MobileNetVaForImageClassification(_UpperCamelCase ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(_UpperCamelCase, _UpperCamelCase, _UpperCamelCase ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor SCREAMING_SNAKE_CASE_ = MobileNetVaImageProcessor( crop_size={'''width''': config.image_size, '''height''': config.image_size}, size={'''shortest_edge''': config.image_size + 32}, ) SCREAMING_SNAKE_CASE_ = image_processor(images=prepare_img(), return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = model(**_UpperCamelCase ) SCREAMING_SNAKE_CASE_ = outputs.logits assert logits.shape == (1, 1_001) if model_name == "mobilenet_v1_1.0_224": SCREAMING_SNAKE_CASE_ = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ) elif model_name == "mobilenet_v1_0.75_192": SCREAMING_SNAKE_CASE_ = torch.tensor([-3.9_4_4_0, -2.3_1_4_1, -0.3_3_3_3] ) else: SCREAMING_SNAKE_CASE_ = None if expected_logits is not None: assert torch.allclose(logits[0, :3], _UpperCamelCase, atol=1E-4 ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(F'Saving model {model_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 push_to_hub: print('''Pushing to the hub...''' ) SCREAMING_SNAKE_CASE_ = '''google/''' + model_name image_processor.push_to_hub(_UpperCamelCase ) model.push_to_hub(_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) lowerCAmelCase__ = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
721
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a, __a ): return (preds == labels).mean() @dataclass class snake_case : UpperCAmelCase__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class snake_case : UpperCAmelCase__ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) UpperCAmelCase__ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) UpperCAmelCase__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def _lowerCamelCase ( ): # 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() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1 ), training_args.fpaa, ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''', __a ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE_ = processors[data_args.task_name]() SCREAMING_SNAKE_CASE_ = processor.get_labels() SCREAMING_SNAKE_CASE_ = len(__a ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=__a, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=__a, cache_dir=model_args.cache_dir, ) # Get datasets SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, ) if training_args.do_eval else None ) def compute_metrics(__a ) -> Dict: SCREAMING_SNAKE_CASE_ = np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(__a, p.label_ids )} # Data collator SCREAMING_SNAKE_CASE_ = DataCollatorWithPadding(__a, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE_ = Trainer( model=__a, args=__a, train_dataset=__a, eval_dataset=__a, compute_metrics=__a, data_collator=__a, ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ = trainer.evaluate() SCREAMING_SNAKE_CASE_ = os.path.join(training_args.output_dir, '''eval_results.txt''' ) if trainer.is_world_master(): with open(__a, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''', __a, __a ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__a ) return results def _lowerCamelCase ( __a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
628
0
"""simple docstring""" from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
700
"""simple docstring""" import cva import numpy as np class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if k in (0.04, 0.06): SCREAMING_SNAKE_CASE_ = k SCREAMING_SNAKE_CASE_ = window_size else: raise ValueError('''invalid k value''' ) def __str__(self ): """simple docstring""" return str(self.k ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = cva.imread(SCREAMING_SNAKE_CASE_ , 0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = img.shape SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = img.copy() SCREAMING_SNAKE_CASE_ = cva.cvtColor(SCREAMING_SNAKE_CASE_ , cva.COLOR_GRAY2RGB ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = np.gradient(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = dx**2 SCREAMING_SNAKE_CASE_ = dy**2 SCREAMING_SNAKE_CASE_ = dx * dy SCREAMING_SNAKE_CASE_ = 0.04 SCREAMING_SNAKE_CASE_ = self.window_size // 2 for y in range(SCREAMING_SNAKE_CASE_ , h - offset ): for x in range(SCREAMING_SNAKE_CASE_ , w - offset ): SCREAMING_SNAKE_CASE_ = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = (wxx * wyy) - (wxy**2) SCREAMING_SNAKE_CASE_ = wxx + wyy SCREAMING_SNAKE_CASE_ = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": lowerCAmelCase__ = HarrisCorner(0.04, 3) lowerCAmelCase__, lowerCAmelCase__ = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
628
0
"""simple docstring""" from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case ( __lowercase ): UpperCAmelCase__ = 'new-model' if is_tf_available(): class snake_case ( __lowercase ): UpperCAmelCase__ = NewModelConfig @require_tf class snake_case ( unittest.TestCase ): @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''bert-base-cased''' SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''bert-base-cased''' SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase (self ): """simple docstring""" for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase (self ): """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase (self ): """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase (self ): """simple docstring""" for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase (self ): """simple docstring""" for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase (self ): """simple docstring""" for model_name in ["bert-base-uncased"]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow @require_tensorflow_probability def _lowercase (self ): """simple docstring""" for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModelForTableQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = TFAutoModelForTableQuestionAnswering.from_pretrained( SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE_ ) , 1_44_10 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE_ ) , 1_44_10 ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = copy.deepcopy(model.config ) SCREAMING_SNAKE_CASE_ = ['''FunnelBaseModel'''] SCREAMING_SNAKE_CASE_ = TFAutoModel.from_config(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" try: AutoConfig.register('''new-model''' , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE_ ): auto_class.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) auto_class.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE_ ): auto_class.register(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Now that the config is registered, it can be used as any other config with the auto-API SCREAMING_SNAKE_CASE_ = BertModelTester(self ).get_config() SCREAMING_SNAKE_CASE_ = NewModelConfig(**tiny_config.to_dict() ) SCREAMING_SNAKE_CASE_ = auto_class.from_config(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = auto_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def _lowercase (self ): """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''bert-base is not a local folder and is not a valid model identifier''' ): SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''bert-base''' ) def _lowercase (self ): """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , revision='''aaaaaa''' ) def _lowercase (self ): """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin''' , ): SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model''' ) def _lowercase (self ): """simple docstring""" with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_ , '''Use `from_pt=True` to load this model''' ): SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only''' ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) with RequestCounter() as counter: SCREAMING_SNAKE_CASE_ = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
701
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class snake_case ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.text_to_image( prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = pipe.image_variation(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
628
0
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset lowerCAmelCase__ = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class snake_case ( nn.Module ): def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ = torchvision.models.resnetaaa(pretrained=__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = list(model.children() )[:-2] SCREAMING_SNAKE_CASE_ = nn.Sequential(*__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.pool(self.model(__UpperCamelCase ) ) SCREAMING_SNAKE_CASE_ = torch.flatten(__UpperCamelCase , start_dim=2 ) SCREAMING_SNAKE_CASE_ = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class snake_case ( __snake_case ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [json.loads(__UpperCamelCase ) for l in open(__UpperCamelCase )] SCREAMING_SNAKE_CASE_ = os.path.dirname(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = tokenizer SCREAMING_SNAKE_CASE_ = labels SCREAMING_SNAKE_CASE_ = len(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = max_seq_length SCREAMING_SNAKE_CASE_ = transforms def __len__(self ): """simple docstring""" return len(self.data ) def __getitem__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch.LongTensor(self.tokenizer.encode(self.data[index]['''text'''] , add_special_tokens=__UpperCamelCase ) ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = sentence[0], sentence[1:-1], sentence[-1] SCREAMING_SNAKE_CASE_ = sentence[: self.max_seq_length] SCREAMING_SNAKE_CASE_ = torch.zeros(self.n_classes ) SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = Image.open(os.path.join(self.data_dir , self.data[index]['''img'''] ) ).convert('''RGB''' ) SCREAMING_SNAKE_CASE_ = self.transforms(__UpperCamelCase ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Counter() for row in self.data: label_freqs.update(row['''label'''] ) return label_freqs def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [len(row['''sentence'''] ) for row in batch] SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = len(lowercase__ ), max(lowercase__ ) SCREAMING_SNAKE_CASE_ = torch.zeros(lowercase__, lowercase__, dtype=torch.long ) SCREAMING_SNAKE_CASE_ = torch.zeros(lowercase__, lowercase__, dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(lowercase__, lowercase__ ) ): SCREAMING_SNAKE_CASE_ = input_row['''sentence'''] SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = torch.stack([row['''image'''] for row in batch] ) SCREAMING_SNAKE_CASE_ = torch.stack([row['''label'''] for row in batch] ) SCREAMING_SNAKE_CASE_ = torch.stack([row['''image_start_token'''] for row in batch] ) SCREAMING_SNAKE_CASE_ = torch.stack([row['''image_end_token'''] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def _lowerCamelCase ( ): return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def _lowerCamelCase ( ): return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.4_6_7_7_7_0_4_4, 0.4_4_5_3_1_4_2_9, 0.4_0_6_6_1_0_1_7], std=[0.1_2_2_2_1_9_9_4, 0.1_2_1_4_5_8_3_5, 0.1_4_3_8_0_4_6_9], ), ] )
702
"""simple docstring""" import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def _lowerCamelCase ( __a ): # picklable for multiprocessing return x.sum() def _lowerCamelCase ( __a ): # picklable for multiprocessing return i + 1 @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = [1, 2] SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': [1, 2], '''b''': [3, 4]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 1}, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = [2, 3] SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': [2, 3], '''b''': [4, 5]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 2}, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = 2 self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = {'''a''': np.eye(2 ), '''b''': np.zeros(3 ), '''c''': np.ones(2 )} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 0, '''c''': 2} SCREAMING_SNAKE_CASE_ = { '''a''': np.eye(2 ).astype(SCREAMING_SNAKE_CASE_ ), '''b''': np.zeros(3 ).astype(SCREAMING_SNAKE_CASE_ ), '''c''': np.ones(2 ).astype(SCREAMING_SNAKE_CASE_ ), } self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): # can't pickle a local lambda map_nested(lambda SCREAMING_SNAKE_CASE_ : x + 1 , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 3, '''b''': 4} SCREAMING_SNAKE_CASE_ = {'''a''': 5, '''b''': 6} SCREAMING_SNAKE_CASE_ = sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" class snake_case : UpperCAmelCase__ = '''bar''' SCREAMING_SNAKE_CASE_ = Foo() self.assertEqual(foo.my_attr , '''bar''' ) with temporary_assignment(SCREAMING_SNAKE_CASE_ , '''my_attr''' , '''BAR''' ): self.assertEqual(foo.my_attr , '''BAR''' ) self.assertEqual(foo.my_attr , '''bar''' ) @pytest.mark.parametrize( '''iterable_length, num_proc, expected_num_proc''', [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ], ) def _lowerCamelCase ( __a, __a, __a ): with patch('''datasets.utils.py_utils._single_map_nested''' ) as mock_single_map_nested, patch( '''datasets.parallel.parallel.Pool''' ) as mock_multiprocessing_pool: SCREAMING_SNAKE_CASE_ = {F'{i}': i for i in range(__a )} SCREAMING_SNAKE_CASE_ = map_nested(lambda __a : x + 10, __a, num_proc=__a, parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class snake_case ( __lowercase ): @require_tf def _lowercase (self ): """simple docstring""" import tensorflow as tf from tensorflow.keras import layers SCREAMING_SNAKE_CASE_ = layers.Dense(2 ) def gen_random_output(): SCREAMING_SNAKE_CASE_ = tf.random.uniform((1, 3) ) return model(SCREAMING_SNAKE_CASE_ ).numpy() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def _lowercase (self ): """simple docstring""" import torch def gen_random_output(): SCREAMING_SNAKE_CASE_ = torch.nn.Linear(3 , 2 ) SCREAMING_SNAKE_CASE_ = torch.rand(1 , 3 ) return model(SCREAMING_SNAKE_CASE_ ).detach().numpy() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def _lowercase (self ): """simple docstring""" def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize('''input_data''', [{}] ) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).data assert output_data == input_data @pytest.mark.parametrize( '''data, expected_output''', [ ({}, []), ([], []), ('''foo''', ['''foo''']), (['''foo''', '''bar'''], ['''foo''', '''bar''']), ([['''foo''', '''bar''']], ['''foo''', '''bar''']), ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']), ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']), ({'''a''': 1, '''b''': 2}, [1, 2]), ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]), ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]), ], ) def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).flatten() assert output == expected_output def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = A(x=1, y='''foobar''' ) SCREAMING_SNAKE_CASE_ = {'''x''': 1, '''y''': '''foobar'''} assert asdict(__a ) == expected_output SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': A(x=10, y='''foo''' )}, '''c''': [A(x=20, y='''bar''' )]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]} assert asdict(__a ) == expected_output with pytest.raises(__a ): asdict([1, A(x=10, y='''foo''' )] ) def _lowerCamelCase ( __a ): return text.split() def _lowerCamelCase ( __a ): yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def _lowerCamelCase ( ): with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = [] for yield_time, content in iflatmap_unordered( __a, _aseconds_generator_of_aitems_with_timing, kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__a ) assert out.count('''a''' ) == 2 assert out.count('''b''' ) == 2 assert len(__a ) == 4
628
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } lowerCAmelCase__ = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = {} with open(lowerCAmelCase_, '''r''' ) as file: for line_number, line in enumerate(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE_ = line.strip() if line: SCREAMING_SNAKE_CASE_ = line.split() SCREAMING_SNAKE_CASE_ = line_number SCREAMING_SNAKE_CASE_ = words[0] SCREAMING_SNAKE_CASE_ = value return result def _lowerCamelCase ( __a, __a, __a, __a, __a ): for attribute in key.split('''.''' ): SCREAMING_SNAKE_CASE_ = getattr(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE_ = PARAM_MAPPING[full_name.split('''.''' )[-1]] SCREAMING_SNAKE_CASE_ = '''param''' if weight_type is not None and weight_type != "param": SCREAMING_SNAKE_CASE_ = getattr(lowerCAmelCase_, lowerCAmelCase_ ).shape elif weight_type is not None and weight_type == "param": SCREAMING_SNAKE_CASE_ = hf_pointer for attribute in hf_param_name.split('''.''' ): SCREAMING_SNAKE_CASE_ = getattr(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = shape_pointer.shape # let's reduce dimension SCREAMING_SNAKE_CASE_ = value[0] else: SCREAMING_SNAKE_CASE_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE_ = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE_ = value elif weight_type == "bias": SCREAMING_SNAKE_CASE_ = value elif weight_type == "param": for attribute in hf_param_name.split('''.''' ): SCREAMING_SNAKE_CASE_ = getattr(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = value else: SCREAMING_SNAKE_CASE_ = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def _lowerCamelCase ( __a, __a, __a, __a, __a ): SCREAMING_SNAKE_CASE_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE_ = PARAM_MAPPING[full_name.split('''.''' )[-1]] SCREAMING_SNAKE_CASE_ = '''param''' if weight_type is not None and weight_type != "param": SCREAMING_SNAKE_CASE_ = '''.'''.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": SCREAMING_SNAKE_CASE_ = '''.'''.join([key, hf_param_name] ) else: SCREAMING_SNAKE_CASE_ = key SCREAMING_SNAKE_CASE_ = value if '''lm_head''' in full_key else value[0] lowerCAmelCase__ = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _lowerCamelCase ( __a, __a, __a=None, __a=None ): SCREAMING_SNAKE_CASE_ = False for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE_ = '''wav2vec2.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: SCREAMING_SNAKE_CASE_ = True if "*" in mapped_key: SCREAMING_SNAKE_CASE_ = name.split(lowerCAmelCase_ )[0].split('''.''' )[-2] SCREAMING_SNAKE_CASE_ = mapped_key.replace('''*''', lowerCAmelCase_ ) if "weight_g" in name: SCREAMING_SNAKE_CASE_ = '''weight_g''' elif "weight_v" in name: SCREAMING_SNAKE_CASE_ = '''weight_v''' elif "bias" in name: SCREAMING_SNAKE_CASE_ = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj SCREAMING_SNAKE_CASE_ = '''weight''' else: SCREAMING_SNAKE_CASE_ = None if hf_dict is not None: rename_dict(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) else: set_recursively(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return is_used return is_used def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = fairseq_model.state_dict() SCREAMING_SNAKE_CASE_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE_ = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, hf_model.config.feat_extract_norm == '''group''', ) SCREAMING_SNAKE_CASE_ = True else: SCREAMING_SNAKE_CASE_ = load_wavaveca_layer(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) if not is_used: unused_weights.append(lowerCAmelCase_ ) logger.warning(F'Unused weights: {unused_weights}' ) def _lowerCamelCase ( __a, __a, __a, __a, __a ): SCREAMING_SNAKE_CASE_ = full_name.split('''conv_layers.''' )[-1] SCREAMING_SNAKE_CASE_ = name.split('''.''' ) SCREAMING_SNAKE_CASE_ = int(items[0] ) SCREAMING_SNAKE_CASE_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) SCREAMING_SNAKE_CASE_ = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) SCREAMING_SNAKE_CASE_ = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.' ) SCREAMING_SNAKE_CASE_ = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.' ) SCREAMING_SNAKE_CASE_ = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowerCAmelCase_ ) @torch.no_grad() def _lowerCamelCase ( __a, __a, __a=None, __a=None, __a=True, __a=False ): if config_path is not None: SCREAMING_SNAKE_CASE_ = WavaVecaConfig.from_pretrained(lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE_ = WavaVecaConfig() if is_seq_class: SCREAMING_SNAKE_CASE_ = read_txt_into_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = idalabel SCREAMING_SNAKE_CASE_ = WavaVecaForSequenceClassification(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=16_000, padding_value=0, do_normalize=lowerCAmelCase_, return_attention_mask=lowerCAmelCase_, ) feature_extractor.save_pretrained(lowerCAmelCase_ ) elif is_finetuned: if dict_path: SCREAMING_SNAKE_CASE_ = Dictionary.load(lowerCAmelCase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq SCREAMING_SNAKE_CASE_ = target_dict.pad_index SCREAMING_SNAKE_CASE_ = target_dict.bos_index SCREAMING_SNAKE_CASE_ = target_dict.eos_index SCREAMING_SNAKE_CASE_ = len(target_dict.symbols ) SCREAMING_SNAKE_CASE_ = os.path.join(lowerCAmelCase_, '''vocab.json''' ) if not os.path.isdir(lowerCAmelCase_ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowerCAmelCase_ ) ) return os.makedirs(lowerCAmelCase_, exist_ok=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = target_dict.indices # fairseq has the <pad> and <s> switched SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 with open(lowerCAmelCase_, '''w''', encoding='''utf-8''' ) as vocab_handle: json.dump(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = WavaVecaCTCTokenizer( lowerCAmelCase_, unk_token=target_dict.unk_word, pad_token=target_dict.pad_word, bos_token=target_dict.bos_word, eos_token=target_dict.eos_word, word_delimiter_token='''|''', do_lower_case=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE_ = True if config.feat_extract_norm == '''layer''' else False SCREAMING_SNAKE_CASE_ = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=16_000, padding_value=0, do_normalize=lowerCAmelCase_, return_attention_mask=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE_ = WavaVecaProcessor(feature_extractor=lowerCAmelCase_, tokenizer=lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = WavaVecaForCTC(lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE_ = WavaVecaForPreTraining(lowerCAmelCase_ ) if is_finetuned or is_seq_class: SCREAMING_SNAKE_CASE_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: SCREAMING_SNAKE_CASE_ = argparse.Namespace(task='''audio_pretraining''' ) SCREAMING_SNAKE_CASE_ = fairseq.tasks.setup_task(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path], task=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE_ = model[0].eval() recursively_load_weights(lowerCAmelCase_, lowerCAmelCase_, not is_finetuned ) hf_wavavec.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
703
"""simple docstring""" import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCAmelCase__ = { 'facebook/maskformer-swin-base-ade': ( 'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowerCAmelCase__ = logging.get_logger(__name__) class snake_case ( __lowercase ): UpperCAmelCase__ = '''maskformer''' UpperCAmelCase__ = {'''hidden_size''': '''mask_feature_size'''} UpperCAmelCase__ = ['''resnet''', '''swin'''] UpperCAmelCase__ = ['''detr'''] def __init__(self , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 20.0 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k SCREAMING_SNAKE_CASE_ = SwinConfig( image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = backbone_config.pop('''model_type''' ) SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ' f'Supported model types: {",".join(self.backbones_supported )}' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 SCREAMING_SNAKE_CASE_ = DetrConfig() else: # verify that the decoder is supported SCREAMING_SNAKE_CASE_ = ( decoder_config.pop('''model_type''' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'Transformer Decoder {decoder_type} not supported, please use one of' f' {",".join(self.decoders_supported )}' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[decoder_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = backbone_config SCREAMING_SNAKE_CASE_ = decoder_config # main feature dimension for the model SCREAMING_SNAKE_CASE_ = fpn_feature_size SCREAMING_SNAKE_CASE_ = mask_feature_size # initializer SCREAMING_SNAKE_CASE_ = init_std SCREAMING_SNAKE_CASE_ = init_xavier_std # Hungarian matcher && loss SCREAMING_SNAKE_CASE_ = cross_entropy_weight SCREAMING_SNAKE_CASE_ = dice_weight SCREAMING_SNAKE_CASE_ = mask_weight SCREAMING_SNAKE_CASE_ = use_auxiliary_loss SCREAMING_SNAKE_CASE_ = no_object_weight SCREAMING_SNAKE_CASE_ = output_auxiliary_logits SCREAMING_SNAKE_CASE_ = self.decoder_config.encoder_attention_heads SCREAMING_SNAKE_CASE_ = self.decoder_config.num_hidden_layers super().__init__(**SCREAMING_SNAKE_CASE_ ) @classmethod def _lowercase (cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return cls( backbone_config=SCREAMING_SNAKE_CASE_ , decoder_config=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ = self.decoder_config.to_dict() SCREAMING_SNAKE_CASE_ = self.__class__.model_type return output
628
0
"""simple docstring""" from PIL import Image def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = (259 * (level + 255)) / (255 * (259 - level)) def contrast(__a ) -> int: return int(128 + factor * (c - 128) ) return img.point(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change contrast to 170 lowerCAmelCase__ = change_contrast(img, 170) cont_img.save('image_data/lena_high_contrast.png', format='png')
704
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] SCREAMING_SNAKE_CASE_ = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE_ = [4, 4, 4, 4] SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE_ = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE_ = 128 elif "large" in model_name: SCREAMING_SNAKE_CASE_ = 192 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE_ = 256 elif "huge" in model_name: SCREAMING_SNAKE_CASE_ = 352 # set label information SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE_ = '''imagenet-22k-id2label.json''' else: SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(__a, __a, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = FocalNetConfig( embed_dim=__a, depths=__a, focal_levels=__a, focal_windows=__a, use_conv_embed=__a, idalabel=__a, labelaid=__a, use_post_layernorm=__a, use_layerscale=__a, ) return config def _lowerCamelCase ( __a ): 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 "layers" in name: SCREAMING_SNAKE_CASE_ = '''encoder.''' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE_ = name.replace('''encoder.layers''', '''encoder.stages''' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('''downsample.proj''', '''downsample.projection''' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ = name.replace('''blocks''', '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.f''', '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.h''', '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.proj''', '''modulation.projection_out''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE_ = '''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE_ = '''layernorm.bias''' if "head" in name: SCREAMING_SNAKE_CASE_ = name.replace('''head''', '''classifier''' ) else: SCREAMING_SNAKE_CASE_ = '''focalnet.''' + name return name def _lowerCamelCase ( __a, __a, __a=False ): # fmt: off SCREAMING_SNAKE_CASE_ = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on SCREAMING_SNAKE_CASE_ = model_name_to_url[model_name] print('''Checkpoint URL: ''', __a ) SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(__a, map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = get_focalnet_config(__a ) SCREAMING_SNAKE_CASE_ = FocalNetForImageClassification(__a ) model.eval() # load state dict model.load_state_dict(__a ) # verify conversion SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = BitImageProcessor( do_resize=__a, size={'''shortest_edge''': 256}, resample=PILImageResampling.BILINEAR, do_center_crop=__a, crop_size=224, do_normalize=__a, image_mean=__a, image_std=__a, ) SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__a, stream=__a ).raw ) SCREAMING_SNAKE_CASE_ = processor(images=__a, return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE_ = image_transforms(__a ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values, __a, atol=1E-4 ) SCREAMING_SNAKE_CASE_ = model(**__a ) SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(-1 ).item() print('''Predicted class:''', model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''', outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE_ = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE_ = torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8] ) assert torch.allclose(outputs.logits[0, :3], __a, atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model and processor of {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if push_to_hub: print(F'Pushing model and processor of {model_name} to the hub...' ) model.push_to_hub(F'{model_name}' ) processor.push_to_hub(F'{model_name}' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
628
0
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( __SCREAMING_SNAKE_CASE ): UpperCAmelCase__ = ['''image_processor''', '''tokenizer'''] UpperCAmelCase__ = '''CLIPImageProcessor''' UpperCAmelCase__ = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): """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.''' , __snake_case , ) 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__(__snake_case , __snake_case ) def __call__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): """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(__snake_case , return_tensors=__snake_case , **__snake_case ) if images is not None: SCREAMING_SNAKE_CASE_ = self.image_processor(__snake_case , return_tensors=__snake_case , **__snake_case ) 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(**__snake_case ) , tensor_type=__snake_case ) def _lowercase (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.tokenizer.batch_decode(*__snake_case , **__snake_case ) def _lowercase (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.tokenizer.decode(*__snake_case , **__snake_case ) @property def _lowercase (self ): """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 _lowercase (self ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __snake_case , ) return self.image_processor_class @property def _lowercase (self ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __snake_case , ) return self.image_processor
705
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class snake_case ( __lowercase ): UpperCAmelCase__ = '''glpn''' def __init__(self , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[8, 4, 2, 1] , SCREAMING_SNAKE_CASE_=[32, 64, 1_60, 2_56] , SCREAMING_SNAKE_CASE_=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE_=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[1, 2, 5, 8] , SCREAMING_SNAKE_CASE_=[4, 4, 4, 4] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1e-6 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=-1 , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) 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_ = initializer_range SCREAMING_SNAKE_CASE_ = drop_path_rate SCREAMING_SNAKE_CASE_ = layer_norm_eps SCREAMING_SNAKE_CASE_ = decoder_hidden_size SCREAMING_SNAKE_CASE_ = max_depth SCREAMING_SNAKE_CASE_ = head_in_index
628
0
"""simple docstring""" from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class snake_case ( __lowercase ): def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return 0.0 def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) SCREAMING_SNAKE_CASE_ = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 512 SCREAMING_SNAKE_CASE_ = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_ = [filter_type.process(__a ) for item in inputs] SCREAMING_SNAKE_CASE_ = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_ = np.abs(np.fft.fft(__a ) ) SCREAMING_SNAKE_CASE_ = 20 * np.logaa(__a ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1 ) plt.xlabel('''Frequency (Hz)''' ) plt.xscale('''log''' ) # Display within reasonable bounds SCREAMING_SNAKE_CASE_ = get_bounds(__a, __a ) plt.ylim(max([-80, bounds[0]] ), min([80, bounds[1]] ) ) plt.ylabel('''Gain (dB)''' ) plt.plot(__a ) plt.show() def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 512 SCREAMING_SNAKE_CASE_ = [1] + [0] * (size - 1) SCREAMING_SNAKE_CASE_ = [filter_type.process(__a ) for item in inputs] SCREAMING_SNAKE_CASE_ = [0] * (samplerate - size) # zero-padding outputs += filler SCREAMING_SNAKE_CASE_ = np.angle(np.fft.fft(__a ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1 ) plt.xlabel('''Frequency (Hz)''' ) plt.xscale('''log''' ) plt.ylim(-2 * pi, 2 * pi ) plt.ylabel('''Phase shift (Radians)''' ) plt.plot(np.unwrap(__a, -2 * pi ) ) plt.show()
706
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = KandinskyVaaControlnetPipeline UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''hint'''] UpperCAmelCase__ = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCAmelCase__ = False @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return 32 @property def _lowercase (self ): """simple docstring""" return self.time_input_dim @property def _lowercase (self ): """simple docstring""" return self.time_input_dim * 4 @property def _lowercase (self ): """simple docstring""" return 1_00 @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE_ = UNetaDConditionModel(**SCREAMING_SNAKE_CASE_ ) return model @property def _lowercase (self ): """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = VQModel(**self.dummy_movq_kwargs ) return model def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.dummy_unet SCREAMING_SNAKE_CASE_ = self.dummy_movq SCREAMING_SNAKE_CASE_ = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='''linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=SCREAMING_SNAKE_CASE_ , set_alpha_to_one=SCREAMING_SNAKE_CASE_ , steps_offset=1 , prediction_type='''epsilon''' , thresholding=SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE_ = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): """simple docstring""" SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( SCREAMING_SNAKE_CASE_ ) # create hint SCREAMING_SNAKE_CASE_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): SCREAMING_SNAKE_CASE_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = { '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 64, '''width''': 64, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''cpu''' SCREAMING_SNAKE_CASE_ = self.get_dummy_components() SCREAMING_SNAKE_CASE_ = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = output.images SCREAMING_SNAKE_CASE_ = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) , return_dict=SCREAMING_SNAKE_CASE_ , )[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.6_95_98_26, 0.86_82_79, 0.7_55_80_92, 0.68_76_94_67, 0.85_80_58_04, 0.65_97_74_96, 0.44_88_53_02, 0.5_95_91_11, 0.4_25_15_95] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy''' ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE_ ) ).float() / 2_55.0 SCREAMING_SNAKE_CASE_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) SCREAMING_SNAKE_CASE_ = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = KandinskyVaaControlnetPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = pipeline.to(SCREAMING_SNAKE_CASE_ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''A robot, 4k photo''' SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = pipe_prior( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cuda''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipeline( image_embeds=SCREAMING_SNAKE_CASE_ , negative_image_embeds=SCREAMING_SNAKE_CASE_ , hint=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=1_00 , output_type='''np''' , ) SCREAMING_SNAKE_CASE_ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
628
0
from collections import defaultdict from math import ceil, sqrt def _lowerCamelCase ( __a = 1_000_000, __a = 10 ): SCREAMING_SNAKE_CASE_ = defaultdict(lowercase_ ) for outer_width in range(3, (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: SCREAMING_SNAKE_CASE_ = max( ceil(sqrt(outer_width * outer_width - t_limit ) ), 1 ) else: SCREAMING_SNAKE_CASE_ = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase_, outer_width - 1, 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
707
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class snake_case ( __lowercase ): UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None class snake_case ( __lowercase ): def __init__(self , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_="cls" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = project_dim SCREAMING_SNAKE_CASE_ = pooler_fn SCREAMING_SNAKE_CASE_ = learn_encoder SCREAMING_SNAKE_CASE_ = use_attention_mask class snake_case ( __lowercase ): UpperCAmelCase__ = [R'''pooler''', R'''logit_scale'''] UpperCAmelCase__ = [R'''position_ids''', R'''predictions.decoder.bias'''] UpperCAmelCase__ = '''roberta''' UpperCAmelCase__ = RobertaSeriesConfig def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = XLMRobertaModel(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = getattr(SCREAMING_SNAKE_CASE_ , '''has_pre_transformation''' , SCREAMING_SNAKE_CASE_ ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = nn.Linear(config.hidden_size , config.project_dim ) SCREAMING_SNAKE_CASE_ = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def _lowercase (self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE_ = self.base_model( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , position_ids=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=SCREAMING_SNAKE_CASE_ , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE_ = outputs['''hidden_states'''][-2] SCREAMING_SNAKE_CASE_ = self.pre_LN(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.transformation_pre(SCREAMING_SNAKE_CASE_ ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE_ = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=SCREAMING_SNAKE_CASE_ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
628
0
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowerCAmelCase__ = imread(r'digital_image_processing/image_data/lena_small.jpg') lowerCAmelCase__ = cvtColor(img, COLOR_BGR2GRAY) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def _lowerCamelCase ( ): with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase, 110 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = canny.gen_gaussian_kernel(9, sigma=1.4 ) # Assert ambiguous array assert resp.all() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = imread('''digital_image_processing/image_data/lena_small.jpg''', 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE_ = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def _lowerCamelCase ( ): assert gg.gaussian_filter(__UpperCamelCase, 5, sigma=0.9 ).all() def _lowerCamelCase ( ): # laplace diagonals SCREAMING_SNAKE_CASE_ = array([[0.2_5, 0.5, 0.2_5], [0.5, -3, 0.5], [0.2_5, 0.5, 0.2_5]] ) SCREAMING_SNAKE_CASE_ = conv.img_convolve(__UpperCamelCase, __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def _lowerCamelCase ( ): assert med.median_filter(__UpperCamelCase, 3 ).any() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = sp.make_sepia(__UpperCamelCase, 20 ) assert sepia.all() def _lowerCamelCase ( __a = "digital_image_processing/image_data/lena_small.jpg" ): SCREAMING_SNAKE_CASE_ = bs.Burkes(imread(__UpperCamelCase, 1 ), 120 ) burkes.process() assert burkes.output_img.any() def _lowerCamelCase ( __a = "digital_image_processing/image_data/lena_small.jpg", ): SCREAMING_SNAKE_CASE_ = rs.NearestNeighbour(imread(__UpperCamelCase, 1 ), 400, 200 ) nn.process() assert nn.output.any() def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE_ = imread(__UpperCamelCase, 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE_ = lbp.get_neighbors_pixel( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE_ = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0, image.shape[0] ): for j in range(0, image.shape[1] ): SCREAMING_SNAKE_CASE_ = lbp.local_binary_value(__UpperCamelCase, __UpperCamelCase, __UpperCamelCase ) assert lbp_image.any()
708
"""simple docstring""" import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def _lowerCamelCase ( __a, __a=0.9_9_9, __a="cosine", ): if alpha_transform_type == "cosine": def alpha_bar_fn(__a ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__a ): return math.exp(t * -1_2.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) SCREAMING_SNAKE_CASE_ = [] for i in range(__a ): SCREAMING_SNAKE_CASE_ = i / num_diffusion_timesteps SCREAMING_SNAKE_CASE_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__a ) / alpha_bar_fn(__a ), __a ) ) return torch.tensor(__a, dtype=torch.floataa ) class snake_case ( __lowercase , __lowercase ): UpperCAmelCase__ = [e.name for e in KarrasDiffusionSchedulers] UpperCAmelCase__ = 2 @register_to_config def __init__(self , SCREAMING_SNAKE_CASE_ = 10_00 , SCREAMING_SNAKE_CASE_ = 0.0_00_85 , SCREAMING_SNAKE_CASE_ = 0.0_12 , SCREAMING_SNAKE_CASE_ = "linear" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "epsilon" , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = "linspace" , SCREAMING_SNAKE_CASE_ = 0 , ): """simple docstring""" if trained_betas is not None: SCREAMING_SNAKE_CASE_ = torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "linear": SCREAMING_SNAKE_CASE_ = torch.linspace(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. SCREAMING_SNAKE_CASE_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": SCREAMING_SNAKE_CASE_ = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ , alpha_transform_type='''exp''' ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) SCREAMING_SNAKE_CASE_ = 1.0 - self.betas SCREAMING_SNAKE_CASE_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = use_karras_sigmas def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" if schedule_timesteps is None: SCREAMING_SNAKE_CASE_ = self.timesteps SCREAMING_SNAKE_CASE_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: SCREAMING_SNAKE_CASE_ = 1 if len(SCREAMING_SNAKE_CASE_ ) > 1 else 0 else: SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep SCREAMING_SNAKE_CASE_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self ): """simple docstring""" if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = num_inference_steps SCREAMING_SNAKE_CASE_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": SCREAMING_SNAKE_CASE_ = np.linspace(0 , num_train_timesteps - 1 , SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ )[::-1].copy() elif self.config.timestep_spacing == "leading": SCREAMING_SNAKE_CASE_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(0 , SCREAMING_SNAKE_CASE_ ) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": SCREAMING_SNAKE_CASE_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 SCREAMING_SNAKE_CASE_ = (np.arange(SCREAMING_SNAKE_CASE_ , 0 , -step_ratio )).round().copy().astype(SCREAMING_SNAKE_CASE_ ) timesteps -= 1 else: raise ValueError( f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) SCREAMING_SNAKE_CASE_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.interp(SCREAMING_SNAKE_CASE_ , np.arange(0 , len(SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) if self.config.use_karras_sigmas: SCREAMING_SNAKE_CASE_ = self._convert_to_karras(in_sigmas=SCREAMING_SNAKE_CASE_ , num_inference_steps=self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = np.array([self._sigma_to_t(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for sigma in sigmas] ) SCREAMING_SNAKE_CASE_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) SCREAMING_SNAKE_CASE_ = torch.from_numpy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = timesteps.to(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = timesteps.to(device=SCREAMING_SNAKE_CASE_ ) # empty dt and derivative SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter SCREAMING_SNAKE_CASE_ = defaultdict(SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = np.log(SCREAMING_SNAKE_CASE_ ) # get distribution SCREAMING_SNAKE_CASE_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range SCREAMING_SNAKE_CASE_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) SCREAMING_SNAKE_CASE_ = low_idx + 1 SCREAMING_SNAKE_CASE_ = log_sigmas[low_idx] SCREAMING_SNAKE_CASE_ = log_sigmas[high_idx] # interpolate sigmas SCREAMING_SNAKE_CASE_ = (low - log_sigma) / (low - high) SCREAMING_SNAKE_CASE_ = np.clip(SCREAMING_SNAKE_CASE_ , 0 , 1 ) # transform interpolation to time range SCREAMING_SNAKE_CASE_ = (1 - w) * low_idx + w * high_idx SCREAMING_SNAKE_CASE_ = t.reshape(sigma.shape ) return t def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = in_sigmas[-1].item() SCREAMING_SNAKE_CASE_ = in_sigmas[0].item() SCREAMING_SNAKE_CASE_ = 7.0 # 7.0 is the value used in the paper SCREAMING_SNAKE_CASE_ = np.linspace(0 , 1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = sigma_min ** (1 / rho) SCREAMING_SNAKE_CASE_ = sigma_max ** (1 / rho) SCREAMING_SNAKE_CASE_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self ): """simple docstring""" return self.dt is None def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.index_for_timestep(SCREAMING_SNAKE_CASE_ ) # advance index counter by 1 SCREAMING_SNAKE_CASE_ = timestep.cpu().item() if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = self.sigmas[step_index - 1] SCREAMING_SNAKE_CASE_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": SCREAMING_SNAKE_CASE_ = sigma_hat if self.state_in_first_order else sigma_next SCREAMING_SNAKE_CASE_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": SCREAMING_SNAKE_CASE_ = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.config.clip_sample: SCREAMING_SNAKE_CASE_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep SCREAMING_SNAKE_CASE_ = sigma_next - sigma_hat # store for 2nd order step SCREAMING_SNAKE_CASE_ = derivative SCREAMING_SNAKE_CASE_ = dt SCREAMING_SNAKE_CASE_ = sample else: # 2. 2nd order / Heun's method SCREAMING_SNAKE_CASE_ = (sample - pred_original_sample) / sigma_next SCREAMING_SNAKE_CASE_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample SCREAMING_SNAKE_CASE_ = self.dt SCREAMING_SNAKE_CASE_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE_ ): # mps does not support float64 SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = self.timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = timesteps.to(original_samples.device ) SCREAMING_SNAKE_CASE_ = [self.index_for_timestep(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for t in timesteps] SCREAMING_SNAKE_CASE_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): SCREAMING_SNAKE_CASE_ = sigma.unsqueeze(-1 ) SCREAMING_SNAKE_CASE_ = original_samples + noise * sigma return noisy_samples def __len__(self ): """simple docstring""" return self.config.num_train_timesteps
628
0
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort lowerCAmelCase__ = """1""" lowerCAmelCase__ = """0""" lowerCAmelCase__ = """1""" lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('Create inference session...') lowerCAmelCase__ = ["""TensorrtExecutionProvider""", """CUDAExecutionProvider"""] lowerCAmelCase__ = ort.InferenceSession('model.onnx', sess_options=sess_opt, providers=execution_provider) lowerCAmelCase__ = ort.RunOptions() lowerCAmelCase__ = 128 lowerCAmelCase__ = 1 lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) lowerCAmelCase__ = np.ones((batch, sequence), dtype=np.intaa) print('Warm up phase...') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('Start inference...') lowerCAmelCase__ = time.time() lowerCAmelCase__ = 2000 lowerCAmelCase__ = {} for iter in range(max_iters): lowerCAmelCase__ = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('Average Inference Time = {:.3f} ms'.format((time.time() - start_time) * 1000 / max_iters))
709
"""simple docstring""" import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = 8 # DPR tok SCREAMING_SNAKE_CASE_ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , DPR_VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) # BART tok SCREAMING_SNAKE_CASE_ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] SCREAMING_SNAKE_CASE_ = {'''unk_token''': '''<unk>'''} SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''bart_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''vocab_file'''] ) SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , BART_VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self ): """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''dpr_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''bart_tokenizer''' ) ) def _lowercase (self ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''custom''' , ) if from_disk: SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''dataset''' ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''index.faiss''' ) dataset.get_index('''embeddings''' ).save(os.path.join(self.tmpdirname , '''index.faiss''' ) ) dataset.drop_index('''embeddings''' ) dataset.save_to_disk(os.path.join(self.tmpdirname , '''dataset''' ) ) del dataset SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , SCREAMING_SNAKE_CASE_ ) , ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''text''': ['''foo''', '''bar'''], '''title''': ['''Foo''', '''Bar'''], '''embeddings''': [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index('''embeddings''' , string_factory='''Flat''' , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''hf_bert_base.hnswSQ8_correct_phi_128.c_index''' ) dataset.save_faiss_index('''embeddings''' , index_file_name + '''.index.dpr''' ) pickle.dump(dataset['''id'''] , open(index_file_name + '''.index_meta.dpr''' , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , '''psgs_w100.tsv.pkl''' ) SCREAMING_SNAKE_CASE_ = {sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset} pickle.dump(SCREAMING_SNAKE_CASE_ , open(SCREAMING_SNAKE_CASE_ , '''wb''' ) ) SCREAMING_SNAKE_CASE_ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='''legacy''' , index_path=self.tmpdirname , ) SCREAMING_SNAKE_CASE_ = RagRetriever( SCREAMING_SNAKE_CASE_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch('''transformers.models.rag.retrieval_rag.load_dataset''' ) as mock_load_dataset: SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset() retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''embeddings''', '''id''', '''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''id'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''id'''][0] , '''1''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''id'''][0] , '''0''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['''text''', '''title'''] ) self.assertEqual(len(doc_dicts[0]['''text'''] ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(doc_dicts[0]['''text'''][0] , '''bar''' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['''text'''][0] , '''foo''' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever.retrieve(SCREAMING_SNAKE_CASE_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" import torch SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) SCREAMING_SNAKE_CASE_ = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = ( # noqa: F841 out['''context_input_ids'''], out['''context_attention_mask'''], out['''retrieved_doc_embeds'''], out['''doc_ids'''], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_dpr_ctx_encoder_tokenizer() SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE_ ) retriever.set_ctx_encoder_tokenizer(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE_ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE_ = retriever(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prefix=retriever.config.generator.prefix , n_docs=SCREAMING_SNAKE_CASE_ ) self.assertEqual( len(SCREAMING_SNAKE_CASE_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''') ) , SCREAMING_SNAKE_CASE_ ) # check for doc token related keys in dictionary.
628
0
"""simple docstring""" import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging lowerCAmelCase__ = logging.get_logger(__name__) def _lowerCamelCase ( __a, __a, __a, __a=False ): try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise if not is_sharded: SCREAMING_SNAKE_CASE_ = os.path.abspath(snake_case_ ) logger.info(F'Loading PyTorch weights from {pt_path}' ) SCREAMING_SNAKE_CASE_ = torch.load(snake_case_, map_location='''cpu''' ) logger.info(F'PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters.' ) SCREAMING_SNAKE_CASE_ = convert_pytorch_state_dict_to_flax(snake_case_, snake_case_ ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files SCREAMING_SNAKE_CASE_ = convert_pytorch_sharded_state_dict_to_flax(snake_case_, snake_case_ ) return flax_state_dict def _lowerCamelCase ( __a, __a, __a, __a, ): def is_key_or_prefix_key_in_dict(__a ) -> bool: return len(set(snake_case_ ) & {key, (model_prefix,) + key} ) > 0 # layer norm SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""scale""",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(snake_case_ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""mean""",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(snake_case_ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""var""",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(snake_case_ ): return renamed_pt_tuple_key, pt_tensor # embedding SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""embedding""",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(snake_case_ ): return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(snake_case_ ): SCREAMING_SNAKE_CASE_ = pt_tensor.transpose(2, 3, 1, 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""kernel""",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(snake_case_ ): SCREAMING_SNAKE_CASE_ = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""weight""",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-1] + ("""bias""",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 SCREAMING_SNAKE_CASE_ = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): SCREAMING_SNAKE_CASE_ = pt_tuple_key[-2] + """_g""" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): SCREAMING_SNAKE_CASE_ = pt_tuple_key[-2] + """_v""" if name is not None: SCREAMING_SNAKE_CASE_ = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def _lowerCamelCase ( __a, __a ): # convert pytorch tensor to numpy SCREAMING_SNAKE_CASE_ = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE_ = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: SCREAMING_SNAKE_CASE_ = flax_model.params["""params"""] else: SCREAMING_SNAKE_CASE_ = flax_model.params SCREAMING_SNAKE_CASE_ = flatten_dict(snake_case_ ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE_ = flatten_dict(flax_model.params['''batch_stats'''] ) random_flax_state_dict.update(snake_case_ ) SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE_ = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE_ = tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary SCREAMING_SNAKE_CASE_ = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE_ = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE_ = rename_key_and_reshape_tensor( snake_case_, snake_case_, snake_case_, snake_case_ ) # add model prefix if necessary SCREAMING_SNAKE_CASE_ = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE_ = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ' F'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: SCREAMING_SNAKE_CASE_ = jnp.asarray(snake_case_ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(snake_case_, snake_case_ ) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE_ = jnp.asarray(snake_case_ ) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE_ = jnp.asarray(snake_case_ ) return unflatten_dict(snake_case_ ) def _lowerCamelCase ( __a, __a ): import torch # Load the index SCREAMING_SNAKE_CASE_ = {} for shard_file in shard_filenames: # load using msgpack utils SCREAMING_SNAKE_CASE_ = torch.load(snake_case_ ) SCREAMING_SNAKE_CASE_ = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE_ = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE_ = flax_model.params["""params"""] SCREAMING_SNAKE_CASE_ = flatten_dict(snake_case_ ) random_flax_state_dict.update(flatten_dict(flax_model.params['''batch_stats'''] ) ) else: SCREAMING_SNAKE_CASE_ = flax_model.params SCREAMING_SNAKE_CASE_ = flatten_dict(snake_case_ ) SCREAMING_SNAKE_CASE_ = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE_ = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE_ = tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary SCREAMING_SNAKE_CASE_ = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE_ = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE_ = rename_key_and_reshape_tensor( snake_case_, snake_case_, snake_case_, snake_case_ ) # add model prefix if necessary SCREAMING_SNAKE_CASE_ = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE_ = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( F'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ' F'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: SCREAMING_SNAKE_CASE_ = jnp.asarray(snake_case_ ) continue if "var" in flax_key[-1]: SCREAMING_SNAKE_CASE_ = jnp.asarray(snake_case_ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(snake_case_, snake_case_ ) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE_ = jnp.asarray(snake_case_ ) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE_ = jnp.asarray(snake_case_ ) return unflatten_dict(snake_case_ ) def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = os.path.abspath(snake_case_ ) logger.info(F'Loading Flax weights from {flax_checkpoint_path}' ) # import correct flax class SCREAMING_SNAKE_CASE_ = getattr(snake_case_, '''Flax''' + model.__class__.__name__ ) # load flax weight dict with open(snake_case_, '''rb''' ) as state_f: try: SCREAMING_SNAKE_CASE_ = from_bytes(snake_case_, state_f.read() ) except UnpicklingError: raise EnvironmentError(F'Unable to convert {flax_checkpoint_path} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(snake_case_, snake_case_ ) def _lowerCamelCase ( __a, __a ): try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa, snake_case_ ) ).values() if any(snake_case_ ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params, snake_case_ ) SCREAMING_SNAKE_CASE_ = flatten_dict(snake_case_ ) SCREAMING_SNAKE_CASE_ = pt_model.state_dict() SCREAMING_SNAKE_CASE_ = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) SCREAMING_SNAKE_CASE_ = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ = flax_key_tuple[0] == pt_model.base_model_prefix SCREAMING_SNAKE_CASE_ = """.""".join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE_ = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE_ = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(snake_case_ ) not in pt_model_dict: # conv layer SCREAMING_SNAKE_CASE_ = flax_key_tuple[:-1] + ("""weight""",) SCREAMING_SNAKE_CASE_ = jnp.transpose(snake_case_, (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(snake_case_ ) not in pt_model_dict: # linear layer SCREAMING_SNAKE_CASE_ = flax_key_tuple[:-1] + ("""weight""",) SCREAMING_SNAKE_CASE_ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: SCREAMING_SNAKE_CASE_ = flax_key_tuple[:-1] + ("""weight""",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE_ = flax_key_tuple[:-1] + ("""running_mean""",) elif "var" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE_ = flax_key_tuple[:-1] + ("""running_var""",) if "batch_stats" in flax_state: SCREAMING_SNAKE_CASE_ = """.""".join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: SCREAMING_SNAKE_CASE_ = """.""".join(snake_case_ ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. SCREAMING_SNAKE_CASE_ = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: SCREAMING_SNAKE_CASE_ = key.split('''.''' ) SCREAMING_SNAKE_CASE_ = None if key_components[-3::2] == ["parametrizations", "original0"]: SCREAMING_SNAKE_CASE_ = key_components[-2] + """_g""" elif key_components[-3::2] == ["parametrizations", "original1"]: SCREAMING_SNAKE_CASE_ = key_components[-2] + """_v""" if name is not None: SCREAMING_SNAKE_CASE_ = key_components[:-3] + [name] SCREAMING_SNAKE_CASE_ = """.""".join(snake_case_ ) SCREAMING_SNAKE_CASE_ = key if flax_key in special_pt_names: SCREAMING_SNAKE_CASE_ = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' F'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ = np.asarray(snake_case_ ) if not isinstance(snake_case_, np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ = torch.from_numpy(snake_case_ ) # remove from missing keys missing_keys.remove(snake_case_ ) else: # weight is not expected by PyTorch model unexpected_keys.append(snake_case_ ) pt_model.load_state_dict(snake_case_ ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ = list(snake_case_ ) if len(snake_case_ ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' F' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' F' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' F' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) else: logger.warning(F'All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n' ) if len(snake_case_ ) > 0: logger.warning( F'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' F' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) else: logger.warning( F'All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n' '''If your task is similar to the task the model of the checkpoint was trained on, ''' F'you can already use {pt_model.__class__.__name__} for predictions without further training.' ) return pt_model
710
"""simple docstring""" from collections.abc import Sequence from queue import Queue class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ = start SCREAMING_SNAKE_CASE_ = end SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = left SCREAMING_SNAKE_CASE_ = right def __repr__(self ): """simple docstring""" return f'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = collection SCREAMING_SNAKE_CASE_ = function if self.collection: SCREAMING_SNAKE_CASE_ = self._build_tree(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" self._update_tree(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self._query_range(self.root , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if start == end: return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.collection[start] ) SCREAMING_SNAKE_CASE_ = (start + end) // 2 SCREAMING_SNAKE_CASE_ = self._build_tree(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self._build_tree(mid + 1 , SCREAMING_SNAKE_CASE_ ) return SegmentTreeNode(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.fn(left.val , right.val ) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == i: SCREAMING_SNAKE_CASE_ = val return if i <= node.mid: self._update_tree(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: self._update_tree(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.fn(node.left.val , node.right.val ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , SCREAMING_SNAKE_CASE_ , node.mid ) , self._query_range(node.right , node.mid + 1 , SCREAMING_SNAKE_CASE_ ) , ) else: # range in right child tree return self._query_range(node.right , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" if self.root is not None: SCREAMING_SNAKE_CASE_ = Queue() queue.put(self.root ) while not queue.empty(): SCREAMING_SNAKE_CASE_ = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('*' * 50) lowerCAmelCase__ = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
628
0
"""simple docstring""" from math import sqrt def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and ( number >= 0 ), "'number' must been an int and positive" SCREAMING_SNAKE_CASE_ = True # 0 and 1 are none primes. if number <= 1: SCREAMING_SNAKE_CASE_ = False for divisor in range(2, int(round(sqrt(__UpperCamelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: SCREAMING_SNAKE_CASE_ = False break # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'status' must been from type bool" return status def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N SCREAMING_SNAKE_CASE_ = list(range(2, n + 1 ) ) SCREAMING_SNAKE_CASE_ = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(__UpperCamelCase ) ): for j in range(i + 1, len(__UpperCamelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): SCREAMING_SNAKE_CASE_ = 0 # filters actual prime numbers. SCREAMING_SNAKE_CASE_ = [x for x in begin_list if x != 0] # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'ans' must been from type list" return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and (n > 2), "'N' must been an int and > 2" SCREAMING_SNAKE_CASE_ = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1 ): if is_prime(__UpperCamelCase ): ans.append(__UpperCamelCase ) # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'ans' must been from type list" return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and number >= 0, "'number' must been an int and >= 0" SCREAMING_SNAKE_CASE_ = [] # this list will be returns of the function. # potential prime number factors. SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = number if number == 0 or number == 1: ans.append(__UpperCamelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(__UpperCamelCase ): while quotient != 1: if is_prime(__UpperCamelCase ) and (quotient % factor == 0): ans.append(__UpperCamelCase ) quotient /= factor else: factor += 1 else: ans.append(__UpperCamelCase ) # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'ans' must been from type list" return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" SCREAMING_SNAKE_CASE_ = 0 # prime factorization of 'number' SCREAMING_SNAKE_CASE_ = prime_factorization(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = max(__UpperCamelCase ) # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'ans' must been from type int" return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" SCREAMING_SNAKE_CASE_ = 0 # prime factorization of 'number' SCREAMING_SNAKE_CASE_ = prime_factorization(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = min(__UpperCamelCase ) # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'ans' must been from type int" return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'number' must been an int" assert isinstance(number % 2 == 0, __UpperCamelCase ), "compare bust been from type bool" return number % 2 == 0 def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ), "'number' must been an int" assert isinstance(number % 2 != 0, __UpperCamelCase ), "compare bust been from type bool" return number % 2 != 0 def _lowerCamelCase ( __a ): '''simple docstring''' assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and (number > 2) and is_even(__UpperCamelCase ) ), "'number' must been an int, even and > 2" SCREAMING_SNAKE_CASE_ = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' SCREAMING_SNAKE_CASE_ = get_prime_numbers(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = len(__UpperCamelCase ) # run variable for while-loops. SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = None # exit variable. for break up the loops SCREAMING_SNAKE_CASE_ = True while i < len_pn and loop: SCREAMING_SNAKE_CASE_ = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: SCREAMING_SNAKE_CASE_ = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and (len(__UpperCamelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def _lowerCamelCase ( __a, __a ): '''simple docstring''' assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and isinstance(__UpperCamelCase, __UpperCamelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." SCREAMING_SNAKE_CASE_ = 0 while numbera != 0: SCREAMING_SNAKE_CASE_ = numbera % numbera SCREAMING_SNAKE_CASE_ = numbera SCREAMING_SNAKE_CASE_ = rest # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def _lowerCamelCase ( __a, __a ): '''simple docstring''' assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and isinstance(__UpperCamelCase, __UpperCamelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." SCREAMING_SNAKE_CASE_ = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' SCREAMING_SNAKE_CASE_ = prime_factorization(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = prime_factorization(__UpperCamelCase ) elif numbera == 1 or numbera == 1: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = max(__UpperCamelCase, __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__UpperCamelCase ) for _ in range(max(__UpperCamelCase, __UpperCamelCase ) ): ans *= n else: SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__UpperCamelCase ) for _ in range(__UpperCamelCase ): ans *= n done.append(__UpperCamelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: SCREAMING_SNAKE_CASE_ = prime_fac_a.count(__UpperCamelCase ) for _ in range(__UpperCamelCase ): ans *= n done.append(__UpperCamelCase ) # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and (n >= 0), "'number' must been a positive int" SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(__UpperCamelCase ): ans += 1 # precondition assert isinstance(__UpperCamelCase, __UpperCamelCase ) and is_prime( __UpperCamelCase ), "'ans' must been a prime number and from type int" return ans def _lowerCamelCase ( __a, __a ): '''simple docstring''' assert ( is_prime(__UpperCamelCase ) and is_prime(__UpperCamelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" SCREAMING_SNAKE_CASE_ = p_number_a + 1 # jump to the next number SCREAMING_SNAKE_CASE_ = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(__UpperCamelCase ): number += 1 while number < p_number_a: ans.append(__UpperCamelCase ) number += 1 # fetch the next prime number. while not is_prime(__UpperCamelCase ): number += 1 # precondition assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and ans[0] != p_number_a and ans[len(__UpperCamelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and (n >= 1), "'n' must been int and >= 1" SCREAMING_SNAKE_CASE_ = [] # will be returned. for divisor in range(1, n + 1 ): if n % divisor == 0: ans.append(__UpperCamelCase ) # precondition assert ans[0] == 1 and ans[len(__UpperCamelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and ( number > 1 ), "'number' must been an int and >= 1" SCREAMING_SNAKE_CASE_ = get_divisors(__UpperCamelCase ) # precondition assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and (divisors[0] == 1) and (divisors[len(__UpperCamelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def _lowerCamelCase ( __a, __a ): '''simple docstring''' assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and isinstance(__UpperCamelCase, __UpperCamelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. SCREAMING_SNAKE_CASE_ = gcd(abs(__UpperCamelCase ), abs(__UpperCamelCase ) ) # precondition assert ( isinstance(__UpperCamelCase, __UpperCamelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and (n >= 0), "'n' must been a int and >= 0" SCREAMING_SNAKE_CASE_ = 1 # this will be return. for factor in range(1, n + 1 ): ans *= factor return ans def _lowerCamelCase ( __a ): '''simple docstring''' assert isinstance(__UpperCamelCase, __UpperCamelCase ) and (n >= 0), "'n' must been an int and >= 0" SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 1 # this will be return for _ in range(n - 1 ): SCREAMING_SNAKE_CASE_ = ans ans += fiba SCREAMING_SNAKE_CASE_ = tmp return ans
711
"""simple docstring""" def _lowerCamelCase ( __a ): if not isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be an integer' raise TypeError(__a ) if number < 1: SCREAMING_SNAKE_CASE_ = F'Input value of [number={number}] must be > 0' raise ValueError(__a ) SCREAMING_SNAKE_CASE_ = 1 for i in range(1, __a ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
628
0
"""simple docstring""" import os import jsonlines import numpy as np from tqdm import tqdm lowerCAmelCase__ = 2048 lowerCAmelCase__ = 4096 lowerCAmelCase__ = 42 lowerCAmelCase__ = os.environ.pop('PROCESS_TRAIN', 'false') lowerCAmelCase__ = {'null': 0, 'short': 1, 'long': 2, 'yes': 3, 'no': 4} def _lowerCamelCase ( __a ): def choose_first(__a, __a=False ): assert isinstance(lowerCamelCase_, lowerCamelCase_ ) if len(lowerCamelCase_ ) == 1: SCREAMING_SNAKE_CASE_ = answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: SCREAMING_SNAKE_CASE_ = {k: [a[k]] for k in a} if len(a['''start_token'''] ) > 0: break return a SCREAMING_SNAKE_CASE_ = {'''id''': example['''id''']} SCREAMING_SNAKE_CASE_ = example['''annotations'''] SCREAMING_SNAKE_CASE_ = annotation['''yes_no_answer'''] if 0 in yes_no_answer or 1 in yes_no_answer: SCREAMING_SNAKE_CASE_ = ['''yes'''] if 1 in yes_no_answer else ['''no'''] SCREAMING_SNAKE_CASE_ = SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = ['''<cls>'''] else: SCREAMING_SNAKE_CASE_ = ['''short'''] SCREAMING_SNAKE_CASE_ = choose_first(annotation['''short_answers'''] ) if len(out['''start_token'''] ) == 0: # answer will be long if short is not available SCREAMING_SNAKE_CASE_ = ['''long'''] SCREAMING_SNAKE_CASE_ = choose_first(annotation['''long_answer'''], is_long_answer=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = [] answer.update(lowerCamelCase_ ) # disregard some samples if len(answer['''start_token'''] ) > 1 or answer["start_token"] == answer["end_token"]: SCREAMING_SNAKE_CASE_ = True else: SCREAMING_SNAKE_CASE_ = False SCREAMING_SNAKE_CASE_ = ['''start_token''', '''end_token''', '''start_byte''', '''end_byte''', '''text'''] if not all(isinstance(answer[k], lowerCamelCase_ ) for k in cols ): raise ValueError('''Issue in ID''', example['''id'''] ) return answer def _lowerCamelCase ( __a, __a=False ): SCREAMING_SNAKE_CASE_ = _get_single_answer(lowerCamelCase_ ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element SCREAMING_SNAKE_CASE_ = example['''document''']['''tokens'''] SCREAMING_SNAKE_CASE_ = [] for i in range(len(doc['''token'''] ) ): if not doc["is_html"][i]: context.append(doc['''token'''][i] ) return { "context": " ".join(lowerCamelCase_ ), "answer": { "start_token": -100, # ignore index in cross-entropy "end_token": -100, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples SCREAMING_SNAKE_CASE_ = ['''start_token''', '''end_token'''] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 SCREAMING_SNAKE_CASE_ = example['''document''']['''tokens'''] SCREAMING_SNAKE_CASE_ = answer['''start_token'''] SCREAMING_SNAKE_CASE_ = answer['''end_token'''] SCREAMING_SNAKE_CASE_ = [] for i in range(len(doc['''token'''] ) ): if not doc["is_html"][i]: context.append(doc['''token'''][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 SCREAMING_SNAKE_CASE_ = ''' '''.join(context[start_token:end_token] ) # checking above code if assertion: SCREAMING_SNAKE_CASE_ = doc['''is_html'''][answer['''start_token'''] : answer['''end_token''']] SCREAMING_SNAKE_CASE_ = doc['''token'''][answer['''start_token'''] : answer['''end_token''']] SCREAMING_SNAKE_CASE_ = ''' '''.join([old[i] for i in range(len(lowerCamelCase_ ) ) if not is_html[i]] ) if new != old: print('''ID:''', example['''id'''] ) print('''New:''', lowerCamelCase_, end='''\n''' ) print('''Old:''', lowerCamelCase_, end='''\n\n''' ) return { "context": " ".join(lowerCamelCase_ ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def _lowerCamelCase ( __a, __a, __a=2_048, __a=4_096, __a=True ): # overlap will be of doc_stride - q_len SCREAMING_SNAKE_CASE_ = get_context_and_ans(lowerCamelCase_, assertion=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ = out['''answer'''] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } SCREAMING_SNAKE_CASE_ = tokenizer(example['''question''']['''text'''], out['''context'''] ).input_ids SCREAMING_SNAKE_CASE_ = input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = input_ids[:q_len] SCREAMING_SNAKE_CASE_ = range(lowerCamelCase_, len(lowerCamelCase_ ), max_length - doc_stride ) for i in doc_start_indices: SCREAMING_SNAKE_CASE_ = i + max_length - q_len SCREAMING_SNAKE_CASE_ = input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer['''category'''][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-100] * len(lowerCamelCase_ ), "end_token": [-100] * len(lowerCamelCase_ ), "category": category, }, } SCREAMING_SNAKE_CASE_ = out['''context'''].split() SCREAMING_SNAKE_CASE_ = splitted_context[answer['''end_token''']] SCREAMING_SNAKE_CASE_ = len( tokenizer( ''' '''.join(splitted_context[: answer['''start_token''']] ), add_special_tokens=lowerCamelCase_, ).input_ids ) SCREAMING_SNAKE_CASE_ = len( tokenizer(''' '''.join(splitted_context[: answer['''end_token''']] ), add_special_tokens=lowerCamelCase_ ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token SCREAMING_SNAKE_CASE_ = len(tokenizer(lowerCamelCase_, add_special_tokens=lowerCamelCase_ ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 SCREAMING_SNAKE_CASE_ = input_ids[answer['''start_token'''] : answer['''end_token'''] + 1] # right & left are inclusive SCREAMING_SNAKE_CASE_ = answer['''start_token'''] SCREAMING_SNAKE_CASE_ = answer['''end_token'''] if assertion: SCREAMING_SNAKE_CASE_ = tokenizer.decode(lowerCamelCase_ ) if answer["span"] != new: print('''ISSUE IN TOKENIZATION''' ) print('''OLD:''', answer['''span'''] ) print('''NEW:''', lowerCamelCase_, end='''\n\n''' ) if len(lowerCamelCase_ ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } SCREAMING_SNAKE_CASE_ = input_ids[:q_len] SCREAMING_SNAKE_CASE_ = range(lowerCamelCase_, len(lowerCamelCase_ ), max_length - doc_stride ) SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] # null, yes, no, long, short for i in doc_start_indices: SCREAMING_SNAKE_CASE_ = i + max_length - q_len SCREAMING_SNAKE_CASE_ = input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: SCREAMING_SNAKE_CASE_ = start_token - i + q_len SCREAMING_SNAKE_CASE_ = end_token - i + q_len answers_category.append(answer['''category'''][0] ) # ["short"] -> "short" else: SCREAMING_SNAKE_CASE_ = -100 SCREAMING_SNAKE_CASE_ = -100 answers_category.append('''null''' ) SCREAMING_SNAKE_CASE_ = inputs[-1][start_token : end_token + 1] answers_start_token.append(lowerCamelCase_ ) answers_end_token.append(lowerCamelCase_ ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print('''ISSUE in strided for ID:''', example['''id'''] ) print('''New:''', tokenizer.decode(lowerCamelCase_ ) ) print('''Old:''', tokenizer.decode(lowerCamelCase_ ), end='''\n\n''' ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def _lowerCamelCase ( __a, __a, __a=2_048, __a=4_096, __a=False ): SCREAMING_SNAKE_CASE_ = get_strided_contexts_and_ans( lowerCamelCase_, lowerCamelCase_, doc_stride=lowerCamelCase_, max_length=lowerCamelCase_, assertion=lowerCamelCase_, ) return example def _lowerCamelCase ( __a, __a ): with jsonlines.open(lowerCamelCase_, '''a''' ) as writer: for example in tqdm(lowerCamelCase_, total=len(lowerCamelCase_ ), desc='''Saving samples ... ''' ): SCREAMING_SNAKE_CASE_ = example['''labels'''] for ids, start, end, cat in zip( example['''input_ids'''], labels['''start_token'''], labels['''end_token'''], labels['''category'''], ): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { '''input_ids''': ids, '''start_token''': start, '''end_token''': end, '''category''': CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer lowerCAmelCase__ = load_dataset('natural_questions') lowerCAmelCase__ = BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base') lowerCAmelCase__ = data['train' if PROCESS_TRAIN == 'true' else 'validation'] lowerCAmelCase__ = { 'tokenizer': tokenizer, 'doc_stride': DOC_STRIDE, 'max_length': MAX_LENGTH, 'assertion': False, } lowerCAmelCase__ = data.map(prepare_inputs, fn_kwargs=fn_kwargs) lowerCAmelCase__ = data.remove_columns(['annotations', 'document', 'id', 'question']) print(data) np.random.seed(SEED) lowerCAmelCase__ = 'nq-training.jsonl' if PROCESS_TRAIN == 'true' else 'nq-validation.jsonl' save_to_disk(data, file_name=cache_file_name)
712
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = len(__a ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: SCREAMING_SNAKE_CASE_ = i + 1 else: SCREAMING_SNAKE_CASE_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f'''{two_pointer([2, 7, 11, 15], 9) = }''')
628
0
"""simple docstring""" from __future__ import annotations class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = order # a_{0} ... a_{k} SCREAMING_SNAKE_CASE_ = [1.0] + [0.0] * order # b_{0} ... b_{k} SCREAMING_SNAKE_CASE_ = [1.0] + [0.0] * order # x[n-1] ... x[n-k] SCREAMING_SNAKE_CASE_ = [0.0] * self.order # y[n-1] ... y[n-k] SCREAMING_SNAKE_CASE_ = [0.0] * self.order def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if len(SCREAMING_SNAKE_CASE_ ) < self.order: SCREAMING_SNAKE_CASE_ = [1.0, *a_coeffs] if len(SCREAMING_SNAKE_CASE_ ) != self.order + 1: SCREAMING_SNAKE_CASE_ = ( f'Expected a_coeffs to have {self.order + 1} elements ' f'for {self.order}-order filter, got {len(SCREAMING_SNAKE_CASE_ )}' ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != self.order + 1: SCREAMING_SNAKE_CASE_ = ( f'Expected b_coeffs to have {self.order + 1} elements ' f'for {self.order}-order filter, got {len(SCREAMING_SNAKE_CASE_ )}' ) raise ValueError(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = a_coeffs SCREAMING_SNAKE_CASE_ = b_coeffs def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) SCREAMING_SNAKE_CASE_ = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] SCREAMING_SNAKE_CASE_ = self.input_history[:-1] SCREAMING_SNAKE_CASE_ = self.output_history[:-1] SCREAMING_SNAKE_CASE_ = sample SCREAMING_SNAKE_CASE_ = result return result
713
"""simple docstring""" import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a=2, __a=3, __a=16, __a = 10, __a = 2 ): def get_dataset(__a ): SCREAMING_SNAKE_CASE_ = torch.randn(batch_size * n_batches, 1 ) return TensorDataset(__a, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1 ) ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = get_dataset(__a ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) SCREAMING_SNAKE_CASE_ = DataLoader(__a, shuffle=__a, batch_size=__a, num_workers=4 ) return (train_dataloader, valid_dataloader) def _lowerCamelCase ( __a, __a, __a, __a, __a, __a=None ): SCREAMING_SNAKE_CASE_ = [] for epoch in range(__a ): # Train quickly model.train() for batch in dataloader: SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = batch SCREAMING_SNAKE_CASE_ = model(__a ) SCREAMING_SNAKE_CASE_ = torch.nn.functional.mse_loss(__a, __a ) accelerator.backward(__a ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class snake_case ( nn.Module ): def __init__(self ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.randn(1 ) ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return x * self.a + self.b class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(total_limit=1 , project_dir=SCREAMING_SNAKE_CASE_ , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''initial''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = Accelerator() SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything SCREAMING_SNAKE_CASE_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoint''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) # Load everything back in and make sure all states work accelerator.load_state(SCREAMING_SNAKE_CASE_ ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() SCREAMING_SNAKE_CASE_ = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() # Train partially set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_1''' ) ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((SCREAMING_SNAKE_CASE_) ,(SCREAMING_SNAKE_CASE_)) = model.a.item(), model.b.item() SCREAMING_SNAKE_CASE_ = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch.tensor([1, 2, 3] ) SCREAMING_SNAKE_CASE_ = torch.tensor([2, 3, 4] ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(net.parameters() ) SCREAMING_SNAKE_CASE_ = Accelerator() with self.assertRaises(SCREAMING_SNAKE_CASE_ ) as ve: accelerator.register_for_checkpointing(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = str(ve.exception ) self.assertTrue('''Item at index 0''' in message ) self.assertTrue('''Item at index 1''' in message ) self.assertFalse('''Item at index 2''' in message ) self.assertFalse('''Item at index 3''' in message ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) SCREAMING_SNAKE_CASE_ = torch.optim.lr_scheduler.StepLR(SCREAMING_SNAKE_CASE_ , step_size=1 , gamma=0.99 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = dummy_dataloaders() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() SCREAMING_SNAKE_CASE_ = scheduler.state_dict() train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) self.assertEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) def _lowercase (self ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) SCREAMING_SNAKE_CASE_ = DummyModel() SCREAMING_SNAKE_CASE_ = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ , total_limit=2 ) # Train baseline SCREAMING_SNAKE_CASE_ = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_9''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_10''' ) ) ) @require_cuda def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() ) if __name__ == "__main__": lowerCAmelCase__ = '/tmp/accelerate/state_checkpointing' lowerCAmelCase__ = DummyModel() lowerCAmelCase__ = torch.optim.Adam(params=model.parameters(), lr=1e-3) lowerCAmelCase__ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) lowerCAmelCase__, lowerCAmelCase__ = dummy_dataloaders() lowerCAmelCase__ = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline lowerCAmelCase__ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) lowerCAmelCase__, lowerCAmelCase__ = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert param_device.type == accelerator.device.type lowerCAmelCase__ = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: lowerCAmelCase__ = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
628
0
"""simple docstring""" import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a ): return params[F'{prefix}/{prefix}/relpos_bias/rel_embedding'][:, i, :] def _lowerCamelCase ( __a, __a, __a, __a="attention" ): SCREAMING_SNAKE_CASE_ = SCREAMING_SNAKE_CASE_ = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/key/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE_ = k_tmp.reshape(k_tmp.shape[0], k_tmp.shape[1] * k_tmp.shape[2] ) SCREAMING_SNAKE_CASE_ = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/out/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE_ = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1], o_tmp.shape[2] ) SCREAMING_SNAKE_CASE_ = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/query/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE_ = q_tmp.reshape(q_tmp.shape[0], q_tmp.shape[1] * q_tmp.shape[2] ) SCREAMING_SNAKE_CASE_ = np.ascontiguousarray(params[F'{prefix}/{prefix}/{layer_name}/value/kernel'][:, i, :, :] ) SCREAMING_SNAKE_CASE_ = v_tmp.reshape(v_tmp.shape[0], v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def _lowerCamelCase ( __a, __a, __a, __a=False ): if split_mlp_wi: SCREAMING_SNAKE_CASE_ = params[F'{prefix}/{prefix}/mlp/wi_0/kernel'][:, i, :] SCREAMING_SNAKE_CASE_ = params[F'{prefix}/{prefix}/mlp/wi_1/kernel'][:, i, :] SCREAMING_SNAKE_CASE_ = (wi_a, wi_a) else: SCREAMING_SNAKE_CASE_ = params[F'{prefix}/{prefix}/mlp/wi/kernel'][:, i, :] SCREAMING_SNAKE_CASE_ = params[F'{prefix}/{prefix}/mlp/wo/kernel'][:, i, :] return wi, wo def _lowerCamelCase ( __a, __a, __a, __a ): return params[F'{prefix}/{prefix}/{layer_name}/scale'][:, i] def _lowerCamelCase ( __a, *, __a, __a, __a = False ): SCREAMING_SNAKE_CASE_ = traverse_util.flatten_dict(variables['''target'''] ) SCREAMING_SNAKE_CASE_ = {'''/'''.join(a__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi SCREAMING_SNAKE_CASE_ = '''encoder/encoder/mlp/wi_0/kernel''' in old print('''Split MLP:''', a__ ) SCREAMING_SNAKE_CASE_ = collections.OrderedDict() # Shared embeddings. SCREAMING_SNAKE_CASE_ = old['''token_embedder/embedding'''] # Encoder. for i in range(a__ ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE_ = tax_layer_norm_lookup(a__, a__, '''encoder''', '''pre_attention_layer_norm''' ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = tax_attention_lookup(a__, a__, '''encoder''', '''attention''' ) SCREAMING_SNAKE_CASE_ = layer_norm SCREAMING_SNAKE_CASE_ = k.T SCREAMING_SNAKE_CASE_ = o.T SCREAMING_SNAKE_CASE_ = q.T SCREAMING_SNAKE_CASE_ = v.T # Block i, layer 1 (MLP). SCREAMING_SNAKE_CASE_ = tax_layer_norm_lookup(a__, a__, '''encoder''', '''pre_mlp_layer_norm''' ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = tax_mlp_lookup(a__, a__, '''encoder''', a__ ) SCREAMING_SNAKE_CASE_ = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE_ = wi[0].T SCREAMING_SNAKE_CASE_ = wi[1].T else: SCREAMING_SNAKE_CASE_ = wi.T SCREAMING_SNAKE_CASE_ = wo.T if scalable_attention: # convert the rel_embedding of each layer SCREAMING_SNAKE_CASE_ = tax_relpos_bias_lookup( a__, a__, '''encoder''' ).T SCREAMING_SNAKE_CASE_ = old['''encoder/encoder_norm/scale'''] if not scalable_attention: SCREAMING_SNAKE_CASE_ = tax_relpos_bias_lookup( a__, 0, '''encoder''' ).T SCREAMING_SNAKE_CASE_ = tax_relpos_bias_lookup( a__, 0, '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(a__ ): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE_ = tax_layer_norm_lookup(a__, a__, '''decoder''', '''pre_self_attention_layer_norm''' ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = tax_attention_lookup(a__, a__, '''decoder''', '''self_attention''' ) SCREAMING_SNAKE_CASE_ = layer_norm SCREAMING_SNAKE_CASE_ = k.T SCREAMING_SNAKE_CASE_ = o.T SCREAMING_SNAKE_CASE_ = q.T SCREAMING_SNAKE_CASE_ = v.T # Block i, layer 1 (Cross Attention). SCREAMING_SNAKE_CASE_ = tax_layer_norm_lookup(a__, a__, '''decoder''', '''pre_cross_attention_layer_norm''' ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = tax_attention_lookup(a__, a__, '''decoder''', '''encoder_decoder_attention''' ) SCREAMING_SNAKE_CASE_ = layer_norm SCREAMING_SNAKE_CASE_ = k.T SCREAMING_SNAKE_CASE_ = o.T SCREAMING_SNAKE_CASE_ = q.T SCREAMING_SNAKE_CASE_ = v.T # Block i, layer 2 (MLP). SCREAMING_SNAKE_CASE_ = tax_layer_norm_lookup(a__, a__, '''decoder''', '''pre_mlp_layer_norm''' ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = tax_mlp_lookup(a__, a__, '''decoder''', a__ ) SCREAMING_SNAKE_CASE_ = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE_ = wi[0].T SCREAMING_SNAKE_CASE_ = wi[1].T else: SCREAMING_SNAKE_CASE_ = wi.T SCREAMING_SNAKE_CASE_ = wo.T if scalable_attention: # convert the rel_embedding of each layer SCREAMING_SNAKE_CASE_ = tax_relpos_bias_lookup(a__, a__, '''decoder''' ).T SCREAMING_SNAKE_CASE_ = old['''decoder/decoder_norm/scale'''] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: SCREAMING_SNAKE_CASE_ = old['''decoder/logits_dense/kernel'''].T return new def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE_ = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE_ = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) SCREAMING_SNAKE_CASE_ = state_dict['''shared.weight'''] return state_dict def _lowerCamelCase ( __a, __a, __a, __a, __a ): SCREAMING_SNAKE_CASE_ = checkpoints.load_tax_checkpoint(a__ ) SCREAMING_SNAKE_CASE_ = convert_tax_to_pytorch( a__, num_layers=config.num_layers, is_encoder_only=a__, scalable_attention=a__ ) SCREAMING_SNAKE_CASE_ = make_state_dict(a__, a__ ) model.load_state_dict(a__, strict=a__ ) def _lowerCamelCase ( __a, __a, __a, __a = False, __a = False, ): SCREAMING_SNAKE_CASE_ = MTaConfig.from_json_file(a__ ) print(F'Building PyTorch model from configuration: {config}' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: SCREAMING_SNAKE_CASE_ = UMTaEncoderModel(a__ ) else: SCREAMING_SNAKE_CASE_ = UMTaForConditionalGeneration(a__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(a__, a__, a__, a__, a__ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(a__ ) # Verify that we can load the checkpoint. model.from_pretrained(a__ ) print('''Done''' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.') # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained T5 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( '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False ) parser.add_argument( '--scalable_attention', action='store_true', help='Whether the model uses scaled attention (umt5 model)', default=False, ) lowerCAmelCase__ = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
714
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class snake_case ( __lowercase ): UpperCAmelCase__ = (DDIMParallelScheduler,) UpperCAmelCase__ = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample return sample def _lowercase (self ): """simple docstring""" for timesteps in [1_00, 5_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_01, 6_01, 4_01, 2_01, 1] ) ) def _lowercase (self ): """simple docstring""" for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE_ , prediction_type=SCREAMING_SNAKE_CASE_ , sample_max_value=SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 5_00] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_20 , 4_00 ) - 0.1_47_71 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_80 , 9_60 ) - 0.3_24_60 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_87 , 4_86 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_99 , 9_98 ) - 0.02 ) ) < 1e-5 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = 10, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) SCREAMING_SNAKE_CASE_ = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 11_47.79_04 ) < 1e-2 assert abs(result_mean.item() - 0.49_82 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop() SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_72.00_67 ) < 1e-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 52.53_02 ) < 1e-2 assert abs(result_mean.item() - 0.06_84 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.82_95 ) < 1e-2 assert abs(result_mean.item() - 0.19_51 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE_ , beta_start=0.01 ) SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_49.07_84 ) < 1e-2 assert abs(result_mean.item() - 0.19_41 ) < 1e-3
628
0
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def _lowerCamelCase ( __a, __a=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'module.blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'module.blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'module.blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'module.blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'module.blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'module.blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'module.blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'module.blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'module.blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'module.blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ('''module.cls_token''', '''vit.embeddings.cls_token'''), ('''module.patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''module.patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''module.pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''module.norm.weight''', '''layernorm.weight'''), ('''module.norm.bias''', '''layernorm.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE_ = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def _lowerCamelCase ( __a, __a, __a=False ): for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE_ = '''''' else: SCREAMING_SNAKE_CASE_ = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE_ = state_dict.pop(F'module.blocks.{i}.attn.qkv.weight' ) SCREAMING_SNAKE_CASE_ = state_dict.pop(F'module.blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE_ = 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 _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(UpperCamelCase__, UpperCamelCase__ ) def _lowerCamelCase ( __a ): # projection head is used in the self-supervised pre-training in MSN, # for downstream task it's not needed. SCREAMING_SNAKE_CASE_ = [ '''module.fc.fc1.weight''', '''module.fc.fc1.bias''', '''module.fc.bn1.weight''', '''module.fc.bn1.bias''', '''module.fc.bn1.running_mean''', '''module.fc.bn1.running_var''', '''module.fc.bn1.num_batches_tracked''', '''module.fc.fc2.weight''', '''module.fc.fc2.bias''', '''module.fc.bn2.weight''', '''module.fc.bn2.bias''', '''module.fc.bn2.running_mean''', '''module.fc.bn2.running_var''', '''module.fc.bn2.num_batches_tracked''', '''module.fc.fc3.weight''', '''module.fc.fc3.bias''', ] for k in ignore_keys: state_dict.pop(UpperCamelCase__, UpperCamelCase__ ) def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = val def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = ViTMSNConfig() SCREAMING_SNAKE_CASE_ = 1_000 SCREAMING_SNAKE_CASE_ = '''datasets/huggingface/label-files''' SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(UpperCamelCase__, UpperCamelCase__ ), '''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()} if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE_ = 384 SCREAMING_SNAKE_CASE_ = 1_536 SCREAMING_SNAKE_CASE_ = 6 elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE_ = 1_024 SCREAMING_SNAKE_CASE_ = 4_096 SCREAMING_SNAKE_CASE_ = 24 SCREAMING_SNAKE_CASE_ = 16 SCREAMING_SNAKE_CASE_ = 0.1 elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE_ = 4 elif "l7" in checkpoint_url: SCREAMING_SNAKE_CASE_ = 7 SCREAMING_SNAKE_CASE_ = 1_024 SCREAMING_SNAKE_CASE_ = 4_096 SCREAMING_SNAKE_CASE_ = 24 SCREAMING_SNAKE_CASE_ = 16 SCREAMING_SNAKE_CASE_ = 0.1 SCREAMING_SNAKE_CASE_ = ViTMSNModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(UpperCamelCase__, map_location='''cpu''' )['''target_encoder'''] SCREAMING_SNAKE_CASE_ = ViTImageProcessor(size=config.image_size ) remove_projection_head(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = create_rename_keys(UpperCamelCase__, base_model=UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) read_in_q_k_v(UpperCamelCase__, UpperCamelCase__, base_model=UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = Image.open(requests.get(UpperCamelCase__, stream=UpperCamelCase__ ).raw ) SCREAMING_SNAKE_CASE_ = ViTImageProcessor( size=config.image_size, image_mean=UpperCamelCase__, image_std=UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = image_processor(images=UpperCamelCase__, return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE_ = model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE_ = torch.tensor([[-1.0_9_1_5, -1.4_8_7_6, -1.1_8_0_9]] ) elif "b16" in checkpoint_url: SCREAMING_SNAKE_CASE_ = torch.tensor([[14.2_889, -18.9_045, 11.7_281]] ) elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE_ = torch.tensor([[41.5_028, -22.8_681, 45.6_475]] ) elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE_ = torch.tensor([[-4.3_8_6_8, 5.2_9_3_2, -0.4_1_3_7]] ) else: SCREAMING_SNAKE_CASE_ = torch.tensor([[-0.1_7_9_2, -0.6_4_6_5, 2.4_2_6_3]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3], UpperCamelCase__, atol=1E-4 ) 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 __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowerCAmelCase__ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
715
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = TransfoXLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''<unk> UNwanted , running''' SCREAMING_SNAKE_CASE_ = '''<unk> unwanted, running''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [0, 4, 8, 7] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' SCREAMING_SNAKE_CASE_ = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = len(SCREAMING_SNAKE_CASE_ ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
628
0
"""simple docstring""" # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib lowerCAmelCase__ = get_logger() lowerCAmelCase__ = None class snake_case ( TensorFormatter[Mapping, '''jax.Array''', Mapping] ): def __init__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__(features=__SCREAMING_SNAKE_CASE ) import jax from jaxlib.xla_client import Device if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError( f'Expected {device} to be a `str` not {type(__SCREAMING_SNAKE_CASE )}, as `jaxlib.xla_extension.Device` ' '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround ''' '''the device with `str()` to get its string identifier that will be internally mapped ''' '''to the actual `jaxlib.xla_extension.Device`.''' ) SCREAMING_SNAKE_CASE_ = device if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: SCREAMING_SNAKE_CASE_ = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f'Device with string identifier {self.device} not listed among the available ' f'devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ' f'device: {str(jax.devices()[0] )}.' ) SCREAMING_SNAKE_CASE_ = str(jax.devices()[0] ) SCREAMING_SNAKE_CASE_ = jnp_array_kwargs @staticmethod def _lowercase (): """simple docstring""" import jax return {str(__SCREAMING_SNAKE_CASE ): device for device in jax.devices()} def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" import jax import jax.numpy as jnp if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and column: if all( isinstance(__SCREAMING_SNAKE_CASE , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(__SCREAMING_SNAKE_CASE , axis=0 ) return column def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" import jax import jax.numpy as jnp if isinstance(__SCREAMING_SNAKE_CASE , (str, bytes, type(__SCREAMING_SNAKE_CASE )) ): return value elif isinstance(__SCREAMING_SNAKE_CASE , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE_ = {} if isinstance(__SCREAMING_SNAKE_CASE , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: SCREAMING_SNAKE_CASE_ = {'''dtype''': jnp.intaa} else: SCREAMING_SNAKE_CASE_ = {'''dtype''': jnp.intaa} elif isinstance(__SCREAMING_SNAKE_CASE , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE_ = {'''dtype''': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(__SCREAMING_SNAKE_CASE , PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = np.asarray(__SCREAMING_SNAKE_CASE ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: SCREAMING_SNAKE_CASE_ = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(__SCREAMING_SNAKE_CASE , **{**default_dtype, **self.jnp_array_kwargs} ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(__SCREAMING_SNAKE_CASE , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(__SCREAMING_SNAKE_CASE , '''__array__''' ) and not isinstance(__SCREAMING_SNAKE_CASE , jax.Array ): SCREAMING_SNAKE_CASE_ = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(__SCREAMING_SNAKE_CASE ) for substruct in data_struct] ) elif isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ): return self._consolidate([self.recursive_tensorize(__SCREAMING_SNAKE_CASE ) for substruct in data_struct] ) return self._tensorize(__SCREAMING_SNAKE_CASE ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" return map_nested(self._recursive_tensorize , __SCREAMING_SNAKE_CASE , map_list=__SCREAMING_SNAKE_CASE ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.numpy_arrow_extractor().extract_row(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = self.python_features_decoder.decode_row(__SCREAMING_SNAKE_CASE ) return self.recursive_tensorize(__SCREAMING_SNAKE_CASE ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.numpy_arrow_extractor().extract_column(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = self.python_features_decoder.decode_column(__SCREAMING_SNAKE_CASE , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE_ = self.recursive_tensorize(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = self._consolidate(__SCREAMING_SNAKE_CASE ) return column def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.numpy_arrow_extractor().extract_batch(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = self.python_features_decoder.decode_batch(__SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = self.recursive_tensorize(__SCREAMING_SNAKE_CASE ) for column_name in batch: SCREAMING_SNAKE_CASE_ = self._consolidate(batch[column_name] ) return batch
716
"""simple docstring""" from __future__ import annotations import typing from collections import Counter def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = Counter() for base in range(1, max_perimeter + 1 ): for perpendicular in range(__a, max_perimeter + 1 ): SCREAMING_SNAKE_CASE_ = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__a ): SCREAMING_SNAKE_CASE_ = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _lowerCamelCase ( __a = 1_000 ): SCREAMING_SNAKE_CASE_ = pythagorean_triple(__a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'''Perimeter {solution()} has maximum solutions''')
628
0
"""simple docstring""" import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class snake_case ( UpperCamelCase_ , unittest.TestCase ): UpperCAmelCase__ = VideoToVideoSDPipeline UpperCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'''video'''} ) - {'''image''', '''width''', '''height'''} UpperCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''video'''} ) - {'''image'''} UpperCAmelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} UpperCAmelCase__ = False # No `output_type`. UpperCAmelCase__ = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _lowercase (self ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , ) SCREAMING_SNAKE_CASE_ = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , clip_sample=__a , set_alpha_to_one=__a , ) 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 , sample_size=1_28 , ) 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , hidden_act='''gelu''' , projection_dim=5_12 , ) SCREAMING_SNAKE_CASE_ = CLIPTextModel(__a ) SCREAMING_SNAKE_CASE_ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) SCREAMING_SNAKE_CASE_ = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): """simple docstring""" SCREAMING_SNAKE_CASE_ = floats_tensor((1, 3, 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 ) SCREAMING_SNAKE_CASE_ = { 'prompt': 'A painting of a squirrel eating a burger', 'video': video, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE_ = self.get_dummy_components() SCREAMING_SNAKE_CASE_ = VideoToVideoSDPipeline(**__a ) SCREAMING_SNAKE_CASE_ = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) SCREAMING_SNAKE_CASE_ = self.get_dummy_inputs(__a ) SCREAMING_SNAKE_CASE_ = 'np' SCREAMING_SNAKE_CASE_ = sd_pipe(**__a ).frames SCREAMING_SNAKE_CASE_ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) SCREAMING_SNAKE_CASE_ = np.array([1_06, 1_17, 1_13, 1_74, 1_37, 1_12, 1_48, 1_51, 1_31] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def _lowercase (self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a , expected_max_diff=5e-3 ) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def _lowercase (self ): """simple docstring""" pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' ) def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """simple docstring""" return super().test_progress_bar() @slow @skip_mps class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL''' , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames SCREAMING_SNAKE_CASE_ = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE_ = torch.randn((1, 10, 3, 10_24, 5_76) , generator=__a ) SCREAMING_SNAKE_CASE_ = video.to('''cuda''' ) SCREAMING_SNAKE_CASE_ = 'Spiderman is surfing' SCREAMING_SNAKE_CASE_ = pipe(__a , video=__a , generator=__a , num_inference_steps=3 , output_type='''pt''' ).frames SCREAMING_SNAKE_CASE_ = np.array([-1.0_45_89_84, -1.1_27_92_97, -0.9_66_30_86, -0.91_50_39_06, -0.75_09_76_56] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
717
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _lowerCamelCase ( __a ): if is_torch_version('''<''', '''2.0.0''' ) or not hasattr(__a, '''_dynamo''' ): return False return isinstance(__a, torch._dynamo.eval_frame.OptimizedModule ) def _lowerCamelCase ( __a, __a = True ): SCREAMING_SNAKE_CASE_ = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE_ = is_compiled_module(__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE_ = getattr(__a, '''forward''' ) SCREAMING_SNAKE_CASE_ = model.__dict__.pop('''_original_forward''', __a ) if original_forward is not None: while hasattr(__a, '''__wrapped__''' ): SCREAMING_SNAKE_CASE_ = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE_ = forward if getattr(__a, '''_converted_to_transformer_engine''', __a ): convert_model(__a, to_transformer_engine=__a ) if is_compiled: SCREAMING_SNAKE_CASE_ = model SCREAMING_SNAKE_CASE_ = compiled_model return model def _lowerCamelCase ( ): PartialState().wait_for_everyone() def _lowerCamelCase ( __a, __a ): if PartialState().distributed_type == DistributedType.TPU: xm.save(__a, __a ) elif PartialState().local_process_index == 0: torch.save(__a, __a ) @contextmanager def _lowerCamelCase ( **__a ): for key, value in kwargs.items(): SCREAMING_SNAKE_CASE_ = str(__a ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _lowerCamelCase ( __a ): if not hasattr(__a, '''__qualname__''' ) and not hasattr(__a, '''__name__''' ): SCREAMING_SNAKE_CASE_ = getattr(__a, '''__class__''', __a ) if hasattr(__a, '''__qualname__''' ): return obj.__qualname__ if hasattr(__a, '''__name__''' ): return obj.__name__ return str(__a ) def _lowerCamelCase ( __a, __a ): for key, value in source.items(): if isinstance(__a, __a ): SCREAMING_SNAKE_CASE_ = destination.setdefault(__a, {} ) merge_dicts(__a, __a ) else: SCREAMING_SNAKE_CASE_ = value return destination def _lowerCamelCase ( __a = None ): if port is None: SCREAMING_SNAKE_CASE_ = 29_500 with socket.socket(socket.AF_INET, socket.SOCK_STREAM ) as s: return s.connect_ex(('''localhost''', port) ) == 0
628
0
"""simple docstring""" from random import randint from tempfile import TemporaryFile import numpy as np def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = 0 if start < end: SCREAMING_SNAKE_CASE_ = randint(_lowercase, _lowercase ) SCREAMING_SNAKE_CASE_ = a[end] SCREAMING_SNAKE_CASE_ = a[pivot] SCREAMING_SNAKE_CASE_ = temp SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = _in_place_partition(_lowercase, _lowercase, _lowercase ) count += _in_place_quick_sort(_lowercase, _lowercase, p - 1 ) count += _in_place_quick_sort(_lowercase, p + 1, _lowercase ) return count def _lowerCamelCase ( __a, __a, __a ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = randint(_lowercase, _lowercase ) SCREAMING_SNAKE_CASE_ = a[end] SCREAMING_SNAKE_CASE_ = a[pivot] SCREAMING_SNAKE_CASE_ = temp SCREAMING_SNAKE_CASE_ = start - 1 for index in range(_lowercase, _lowercase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value SCREAMING_SNAKE_CASE_ = new_pivot_index + 1 SCREAMING_SNAKE_CASE_ = a[new_pivot_index] SCREAMING_SNAKE_CASE_ = a[index] SCREAMING_SNAKE_CASE_ = temp SCREAMING_SNAKE_CASE_ = a[new_pivot_index + 1] SCREAMING_SNAKE_CASE_ = a[end] SCREAMING_SNAKE_CASE_ = temp return new_pivot_index + 1, count lowerCAmelCase__ = TemporaryFile() lowerCAmelCase__ = 100 # 1000 elements are to be sorted lowerCAmelCase__, lowerCAmelCase__ = 0, 1 # mean and standard deviation lowerCAmelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print('The array is') print(X) outfile.seek(0) # using the same array lowerCAmelCase__ = np.load(outfile) lowerCAmelCase__ = len(M) - 1 lowerCAmelCase__ = _in_place_quick_sort(M, 0, r) print( 'No of Comparisons for 100 elements selected from a standard normal distribution' 'is :' ) print(z)
718
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = CTRLTokenizer UpperCAmelCase__ = False UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE_ = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] SCREAMING_SNAKE_CASE_ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) SCREAMING_SNAKE_CASE_ = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</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(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' return input_text, output_text def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE_ = '''adapt react readapt apt''' SCREAMING_SNAKE_CASE_ = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE_ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
628
0
"""simple docstring""" import torch from diffusers import DiffusionPipeline class snake_case ( __snake_case ): def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__() self.register_modules(unet=_lowercase , scheduler=_lowercase ) def __call__(self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self.unet(_lowercase , _lowercase ).sample SCREAMING_SNAKE_CASE_ = self.scheduler.step(_lowercase , _lowercase , _lowercase ).prev_sample SCREAMING_SNAKE_CASE_ = scheduler_output - scheduler_output + torch.ones_like(_lowercase ) return result
719
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( __a, __a, __a, __a ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_ = BigBirdConfig.from_json_file(__a ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: SCREAMING_SNAKE_CASE_ = BigBirdForQuestionAnswering(__a ) else: SCREAMING_SNAKE_CASE_ = BigBirdForPreTraining(__a ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__a, __a, is_trivia_qa=__a ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) 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( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) lowerCAmelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
628
0
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): lowerCAmelCase__ = 'pt' elif is_tf_available(): lowerCAmelCase__ = 'tf' else: lowerCAmelCase__ = 'jax' class snake_case ( __lowercase , unittest.TestCase ): UpperCAmelCase__ = PerceiverTokenizer UpperCAmelCase__ = False def _lowercase (self ): """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE_ = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _lowercase (self ): """simple docstring""" return PerceiverTokenizer.from_pretrained('''deepmind/language-perceiver''' ) def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **A__ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=20 , SCREAMING_SNAKE_CASE_=5 ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] for i in range(len(A__ ) ): try: SCREAMING_SNAKE_CASE_ = tokenizer.decode([i] , clean_up_tokenization_spaces=A__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) SCREAMING_SNAKE_CASE_ = list(filter(lambda SCREAMING_SNAKE_CASE_ : re.match(R'''^[ a-zA-Z]+$''' , t[1] ) , A__ ) ) SCREAMING_SNAKE_CASE_ = list(filter(lambda SCREAMING_SNAKE_CASE_ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=A__ ) , A__ ) ) if max_length is not None and len(A__ ) > max_length: SCREAMING_SNAKE_CASE_ = toks[:max_length] if min_length is not None and len(A__ ) < min_length and len(A__ ) > 0: while len(A__ ) < min_length: SCREAMING_SNAKE_CASE_ = toks + toks # toks_str = [t[1] for t in toks] SCREAMING_SNAKE_CASE_ = [t[0] for t in toks] # Ensure consistency SCREAMING_SNAKE_CASE_ = tokenizer.decode(A__ , clean_up_tokenization_spaces=A__ ) if " " not in output_txt and len(A__ ) > 1: SCREAMING_SNAKE_CASE_ = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=A__ ) + """ """ + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=A__ ) ) if with_prefix_space: SCREAMING_SNAKE_CASE_ = """ """ + output_txt SCREAMING_SNAKE_CASE_ = tokenizer.encode(A__ , add_special_tokens=A__ ) return output_txt, output_ids def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.perceiver_tokenizer SCREAMING_SNAKE_CASE_ = """Unicode €.""" SCREAMING_SNAKE_CASE_ = tokenizer(A__ ) SCREAMING_SNAKE_CASE_ = [4, 91, 1_16, 1_11, 1_05, 1_17, 1_06, 1_07, 38, 2_32, 1_36, 1_78, 52, 5] self.assertEqual(encoded['''input_ids'''] , A__ ) # decoding SCREAMING_SNAKE_CASE_ = tokenizer.decode(A__ ) self.assertEqual(A__ , '''[CLS]Unicode €.[SEP]''' ) SCREAMING_SNAKE_CASE_ = tokenizer('''e è é ê ë''' ) SCREAMING_SNAKE_CASE_ = [4, 1_07, 38, 2_01, 1_74, 38, 2_01, 1_75, 38, 2_01, 1_76, 38, 2_01, 1_77, 5] self.assertEqual(encoded['''input_ids'''] , A__ ) # decoding SCREAMING_SNAKE_CASE_ = tokenizer.decode(A__ ) self.assertEqual(A__ , '''[CLS]e è é ê ë[SEP]''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''[CLS]e è é ê ë[SEP]''' ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.perceiver_tokenizer SCREAMING_SNAKE_CASE_ = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] # fmt: off SCREAMING_SNAKE_CASE_ = [4, 71, 38, 1_14, 1_17, 1_16, 1_09, 38, 1_18, 1_03, 1_20, 1_03, 1_09, 1_20, 1_03, 1_18, 1_10, 38, 1_08, 1_17, 1_20, 38, 1_21, 1_23, 1_15, 1_15, 1_03, 1_20, 1_11, 1_28, 1_03, 1_22, 1_11, 1_17, 1_16, 52, 5, 0] # fmt: on SCREAMING_SNAKE_CASE_ = tokenizer(A__ , padding=A__ , return_tensors=A__ ) self.assertIsInstance(A__ , A__ ) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE_ = list(batch.input_ids.numpy()[0] ) else: SCREAMING_SNAKE_CASE_ = list(batch.input_ids.tolist()[0] ) self.assertListEqual(A__ , A__ ) self.assertEqual((2, 38) , batch.input_ids.shape ) self.assertEqual((2, 38) , batch.attention_mask.shape ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.perceiver_tokenizer SCREAMING_SNAKE_CASE_ = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] SCREAMING_SNAKE_CASE_ = tokenizer(A__ , padding=A__ , return_tensors=A__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , A__ ) self.assertIn('''attention_mask''' , A__ ) self.assertNotIn('''decoder_input_ids''' , A__ ) self.assertNotIn('''decoder_attention_mask''' , A__ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.perceiver_tokenizer SCREAMING_SNAKE_CASE_ = [ """Summary of the text.""", """Another summary.""", ] SCREAMING_SNAKE_CASE_ = tokenizer( text_target=A__ , max_length=32 , padding='''max_length''' , truncation=A__ , return_tensors=A__ ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test SCREAMING_SNAKE_CASE_ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = """ He is very happy, UNwant\u00E9d,running""" SCREAMING_SNAKE_CASE_ = tokenizer.encode(A__ , add_special_tokens=A__ ) tokenizer.save_pretrained(A__ ) SCREAMING_SNAKE_CASE_ = tokenizer.__class__.from_pretrained(A__ ) SCREAMING_SNAKE_CASE_ = after_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) shutil.rmtree(A__ ) SCREAMING_SNAKE_CASE_ = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = """ He is very happy, UNwant\u00E9d,running""" tokenizer.add_tokens(['''bim''', '''bambam'''] ) SCREAMING_SNAKE_CASE_ = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) SCREAMING_SNAKE_CASE_ = tokenizer.encode(A__ , add_special_tokens=A__ ) tokenizer.save_pretrained(A__ ) SCREAMING_SNAKE_CASE_ = tokenizer.__class__.from_pretrained(A__ ) SCREAMING_SNAKE_CASE_ = after_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) SCREAMING_SNAKE_CASE_ = tokenizer.__class__.from_pretrained(A__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(A__ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(A__ ) with open(os.path.join(A__ , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: SCREAMING_SNAKE_CASE_ = json.load(A__ ) with open(os.path.join(A__ , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: SCREAMING_SNAKE_CASE_ = json.load(A__ ) SCREAMING_SNAKE_CASE_ = [f'<extra_id_{i}>' for i in range(1_25 )] SCREAMING_SNAKE_CASE_ = added_tokens_extra_ids + [ """an_additional_special_token""" ] SCREAMING_SNAKE_CASE_ = added_tokens_extra_ids + [ """an_additional_special_token""" ] with open(os.path.join(A__ , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(A__ , A__ ) with open(os.path.join(A__ , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(A__ , A__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE_ = tokenizer_class.from_pretrained( A__ , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE_ = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=A__ )] SCREAMING_SNAKE_CASE_ = tokenizer_class.from_pretrained( A__ , additional_special_tokens=A__ , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([1_78] ) , '''�''' ) def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """simple docstring""" pass def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.get_tokenizers(fast=A__ , do_lower_case=A__ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): SCREAMING_SNAKE_CASE_ = ["""[CLS]""", """t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """s""", """t""", """[SEP]"""] SCREAMING_SNAKE_CASE_ = tokenizer.convert_tokens_to_string(A__ ) self.assertIsInstance(A__ , A__ )
720
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name def _lowerCamelCase ( __a ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''', __a, ) if isinstance(__a, torch.Tensor ): return image elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [image] if isinstance(image[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = image[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE_ = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = np.array(__a ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = image.transpose(0, 3, 1, 2 ) SCREAMING_SNAKE_CASE_ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(image[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return image def _lowerCamelCase ( __a ): if isinstance(__a, torch.Tensor ): return mask elif isinstance(__a, PIL.Image.Image ): SCREAMING_SNAKE_CASE_ = [mask] if isinstance(mask[0], PIL.Image.Image ): SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = mask[0].size SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE_ = [np.array(m.convert('''L''' ).resize((w, h), resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE_ = np.concatenate(__a, axis=0 ) SCREAMING_SNAKE_CASE_ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = torch.from_numpy(__a ) elif isinstance(mask[0], torch.Tensor ): SCREAMING_SNAKE_CASE_ = torch.cat(__a, dim=0 ) return mask class snake_case ( __lowercase ): UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 2_50 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = 10 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): """simple docstring""" SCREAMING_SNAKE_CASE_ = image SCREAMING_SNAKE_CASE_ = _preprocess_image(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = _preprocess_mask(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE_ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE_ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) SCREAMING_SNAKE_CASE_ = original_image.shape SCREAMING_SNAKE_CASE_ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) SCREAMING_SNAKE_CASE_ = eta SCREAMING_SNAKE_CASE_ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE_ = generator[0] if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE_ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE_ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE_ = self.scheduler.undo_step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = t SCREAMING_SNAKE_CASE_ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
628
0
class snake_case ( __SCREAMING_SNAKE_CASE ): pass class snake_case ( __SCREAMING_SNAKE_CASE ): pass class snake_case : def __init__(self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [ [], [], [], ] def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" try: if len(self.queues[priority] ) >= 1_00: raise OverflowError('''Maximum queue size is 100''' ) self.queues[priority].append(_a ) except IndexError: raise ValueError('''Valid priorities are 0, 1, and 2''' ) def _lowercase (self ): """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('''All queues are empty''' ) def __str__(self ): """simple docstring""" return "\n".join(f'Priority {i}: {q}' for i, q in enumerate(self.queues ) ) class snake_case : def __init__(self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = [] def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if len(self.queue ) == 1_00: raise OverFlowError('''Maximum queue size is 100''' ) self.queue.append(_a ) def _lowercase (self ): """simple docstring""" if not self.queue: raise UnderFlowError('''The queue is empty''' ) else: SCREAMING_SNAKE_CASE_ = min(self.queue ) self.queue.remove(_a ) return data def __str__(self ): """simple docstring""" return str(self.queue ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = FixedPriorityQueue() fpq.enqueue(0, 10 ) fpq.enqueue(1, 70 ) fpq.enqueue(0, 100 ) fpq.enqueue(2, 1 ) fpq.enqueue(2, 5 ) fpq.enqueue(1, 7 ) fpq.enqueue(2, 4 ) fpq.enqueue(1, 64 ) fpq.enqueue(0, 128 ) print(lowerCAmelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowerCAmelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(lowerCAmelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowerCAmelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
721
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase__ = logging.getLogger(__name__) def _lowerCamelCase ( __a, __a ): return (preds == labels).mean() @dataclass class snake_case : UpperCAmelCase__ = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class snake_case : UpperCAmelCase__ = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys() )} ) UpperCAmelCase__ = field(metadata={'''help''': '''Should contain the data files for the task.'''} ) UpperCAmelCase__ = field( default=128 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase__ = field( default=__lowercase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def _lowerCamelCase ( ): # 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() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''', training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1 ), training_args.fpaa, ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''', __a ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE_ = processors[data_args.task_name]() SCREAMING_SNAKE_CASE_ = processor.get_labels() SCREAMING_SNAKE_CASE_ = len(__a ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=__a, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) SCREAMING_SNAKE_CASE_ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool('''.ckpt''' in model_args.model_name_or_path ), config=__a, cache_dir=model_args.cache_dir, ) # Get datasets SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE_ = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=__a, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, ) if training_args.do_eval else None ) def compute_metrics(__a ) -> Dict: SCREAMING_SNAKE_CASE_ = np.argmax(p.predictions, axis=1 ) return {"acc": simple_accuracy(__a, p.label_ids )} # Data collator SCREAMING_SNAKE_CASE_ = DataCollatorWithPadding(__a, pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE_ = Trainer( model=__a, args=__a, train_dataset=__a, eval_dataset=__a, compute_metrics=__a, data_collator=__a, ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE_ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE_ = trainer.evaluate() SCREAMING_SNAKE_CASE_ = os.path.join(training_args.output_dir, '''eval_results.txt''' ) if trainer.is_world_master(): with open(__a, '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''', __a, __a ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__a ) return results def _lowerCamelCase ( __a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
628
0
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class snake_case ( __lowercase ): UpperCAmelCase__ = "" UpperCAmelCase__ = "hf-legacy" # "hf://"" is reserved for hffs def __init__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(self , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ = repo_info SCREAMING_SNAKE_CASE_ = token SCREAMING_SNAKE_CASE_ = None def _lowercase (self ): """simple docstring""" if self.dir_cache is None: SCREAMING_SNAKE_CASE_ = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE_ = { '''name''': hf_file.rfilename, '''size''': None, '''type''': '''file''', } self.dir_cache.update( { str(UpperCamelCase__ ): {'''name''': str(UpperCamelCase__ ), '''size''': None, '''type''': '''directory'''} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "rb" , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" if not isinstance(self.repo_info , UpperCamelCase__ ): raise NotImplementedError(f'Open is only implemented for dataset repositories, but got {self.repo_info}' ) SCREAMING_SNAKE_CASE_ = hf_hub_url(self.repo_info.id , UpperCamelCase__ , revision=self.repo_info.sha ) return fsspec.open( UpperCamelCase__ , mode=UpperCamelCase__ , headers=get_authentication_headers_for_url(UpperCamelCase__ , use_auth_token=self.token ) , client_kwargs={'''trust_env''': True} , ).open() def _lowercase (self , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" self._get_dirs() SCREAMING_SNAKE_CASE_ = self._strip_protocol(UpperCamelCase__ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(UpperCamelCase__ ) def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" self._get_dirs() SCREAMING_SNAKE_CASE_ = PurePosixPath(path.strip('''/''' ) ) SCREAMING_SNAKE_CASE_ = {} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE_ = PurePosixPath(p.strip('''/''' ) ) SCREAMING_SNAKE_CASE_ = p.parent if root == path: SCREAMING_SNAKE_CASE_ = f SCREAMING_SNAKE_CASE_ = list(paths.values() ) if detail: return out else: return sorted(f['''name'''] for f in out )
700
"""simple docstring""" import cva import numpy as np class snake_case : def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" if k in (0.04, 0.06): SCREAMING_SNAKE_CASE_ = k SCREAMING_SNAKE_CASE_ = window_size else: raise ValueError('''invalid k value''' ) def __str__(self ): """simple docstring""" return str(self.k ) def _lowercase (self , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = cva.imread(SCREAMING_SNAKE_CASE_ , 0 ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = img.shape SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = img.copy() SCREAMING_SNAKE_CASE_ = cva.cvtColor(SCREAMING_SNAKE_CASE_ , cva.COLOR_GRAY2RGB ) SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ = np.gradient(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = dx**2 SCREAMING_SNAKE_CASE_ = dy**2 SCREAMING_SNAKE_CASE_ = dx * dy SCREAMING_SNAKE_CASE_ = 0.04 SCREAMING_SNAKE_CASE_ = self.window_size // 2 for y in range(SCREAMING_SNAKE_CASE_ , h - offset ): for x in range(SCREAMING_SNAKE_CASE_ , w - offset ): SCREAMING_SNAKE_CASE_ = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = (wxx * wyy) - (wxy**2) SCREAMING_SNAKE_CASE_ = wxx + wyy SCREAMING_SNAKE_CASE_ = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": lowerCAmelCase__ = HarrisCorner(0.04, 3) lowerCAmelCase__, lowerCAmelCase__ = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
628
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class snake_case ( snake_case_ ): UpperCAmelCase__ = """realm""" def __init__(self , SCREAMING_SNAKE_CASE_=3_05_22 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=1_28 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=30_72 , SCREAMING_SNAKE_CASE_="gelu_new" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-1_2 , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=1e-3 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=3_20 , SCREAMING_SNAKE_CASE_=13_35_37_18 , SCREAMING_SNAKE_CASE_=50_00 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # Common config SCREAMING_SNAKE_CASE_ = vocab_size SCREAMING_SNAKE_CASE_ = max_position_embeddings SCREAMING_SNAKE_CASE_ = hidden_size SCREAMING_SNAKE_CASE_ = retriever_proj_size SCREAMING_SNAKE_CASE_ = num_hidden_layers SCREAMING_SNAKE_CASE_ = num_attention_heads SCREAMING_SNAKE_CASE_ = num_candidates SCREAMING_SNAKE_CASE_ = intermediate_size SCREAMING_SNAKE_CASE_ = hidden_act SCREAMING_SNAKE_CASE_ = hidden_dropout_prob SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ = initializer_range SCREAMING_SNAKE_CASE_ = type_vocab_size SCREAMING_SNAKE_CASE_ = layer_norm_eps # Reader config SCREAMING_SNAKE_CASE_ = span_hidden_size SCREAMING_SNAKE_CASE_ = max_span_width SCREAMING_SNAKE_CASE_ = reader_layer_norm_eps SCREAMING_SNAKE_CASE_ = reader_beam_size SCREAMING_SNAKE_CASE_ = reader_seq_len # Retrieval config SCREAMING_SNAKE_CASE_ = num_block_records SCREAMING_SNAKE_CASE_ = searcher_beam_size
701
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowerCAmelCase__ = False class snake_case ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case ( unittest.TestCase ): def _lowercase (self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = generator.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt='''first prompt''' , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = '''cyberpunk 2077''' SCREAMING_SNAKE_CASE_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.dual_guided( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , text_to_image_strength=0.75 , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = '''A painting of a squirrel eating a burger ''' SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = pipe.text_to_image( prompt=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 SCREAMING_SNAKE_CASE_ = pipe.image_variation(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE_ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) SCREAMING_SNAKE_CASE_ = np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
628
0
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class snake_case ( unittest.TestCase ): def _lowercase (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = jnp.ones((batch_size, length) ) / length return scores def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(batch_size=2 , length=lowercase__ ) # tweak scores to not be uniform anymore SCREAMING_SNAKE_CASE_ = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch SCREAMING_SNAKE_CASE_ = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax SCREAMING_SNAKE_CASE_ = jax.nn.softmax(lowercase__ , axis=-1 ) SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=1.3 ) SCREAMING_SNAKE_CASE_ = jax.nn.softmax(temp_dist_warper_sharper(lowercase__ , scores.copy() , cur_len=lowercase__ ) , axis=-1 ) SCREAMING_SNAKE_CASE_ = jax.nn.softmax(temp_dist_warper_smoother(lowercase__ , scores.copy() , cur_len=lowercase__ ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 2 # create ramp distribution SCREAMING_SNAKE_CASE_ = np.broadcast_to(np.arange(lowercase__ )[None, :] , (batch_size, vocab_size) ).copy() SCREAMING_SNAKE_CASE_ = ramp_logits[1:, : vocab_size // 2] + vocab_size SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ = top_k_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case SCREAMING_SNAKE_CASE_ = 5 SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) SCREAMING_SNAKE_CASE_ = np.broadcast_to(np.arange(lowercase__ )[None, :] , (batch_size, length) ).copy() SCREAMING_SNAKE_CASE_ = top_k_warp_safety_check(lowercase__ , lowercase__ , cur_len=lowercase__ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) SCREAMING_SNAKE_CASE_ = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.8 ) SCREAMING_SNAKE_CASE_ = np.exp(top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 SCREAMING_SNAKE_CASE_ = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # check edge cases with negative and extreme logits SCREAMING_SNAKE_CASE_ = np.broadcast_to(np.arange(lowercase__ )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme SCREAMING_SNAKE_CASE_ = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) SCREAMING_SNAKE_CASE_ = top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase__ ) # check that min length is applied at length 5 SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, 20) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ = 5 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = min_dist_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = 15 SCREAMING_SNAKE_CASE_ = min_dist_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertFalse(jnp.isinf(lowercase__ ).any() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase__ ) # check that all scores are -inf except the bos_token_id score SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, 1) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertFalse(jnp.isinf(lowercase__ ).any() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 20 SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 5 SCREAMING_SNAKE_CASE_ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase__ , eos_token_id=lowercase__ ) # check that all scores are -inf except the eos_token_id when max_length is reached SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, 4) , vocab_size=20 ) SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached SCREAMING_SNAKE_CASE_ = 3 SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = logits_processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) self.assertFalse(jnp.isinf(lowercase__ ).any() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 15 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, sequence_length) , lowercase__ ) SCREAMING_SNAKE_CASE_ = input_ids.copy() SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase__ , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ = 10 # no processor list SCREAMING_SNAKE_CASE_ = temp_dist_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = top_k_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = min_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = bos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = eos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) # with processor list SCREAMING_SNAKE_CASE_ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE_ = processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = 4 SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 15 SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = 15 # dummy input_ids and scores SCREAMING_SNAKE_CASE_ = ids_tensor((batch_size, sequence_length) , lowercase__ ) SCREAMING_SNAKE_CASE_ = input_ids.copy() SCREAMING_SNAKE_CASE_ = self._get_uniform_logits(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = scores.copy() # instantiate all dist processors SCREAMING_SNAKE_CASE_ = FlaxTemperatureLogitsWarper(temperature=0.5 ) SCREAMING_SNAKE_CASE_ = FlaxTopKLogitsWarper(3 ) SCREAMING_SNAKE_CASE_ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors SCREAMING_SNAKE_CASE_ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase__ , eos_token_id=lowercase__ ) SCREAMING_SNAKE_CASE_ = 10 # no processor list def run_no_processor_list(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = temp_dist_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = top_k_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = top_p_warp(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = min_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = bos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) SCREAMING_SNAKE_CASE_ = eos_dist_proc(lowercase__ , lowercase__ , cur_len=lowercase__ ) return scores # with processor list def run_processor_list(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) SCREAMING_SNAKE_CASE_ = processor(lowercase__ , lowercase__ , cur_len=lowercase__ ) return scores SCREAMING_SNAKE_CASE_ = jax.jit(lowercase__ ) SCREAMING_SNAKE_CASE_ = jax.jit(lowercase__ ) SCREAMING_SNAKE_CASE_ = jitted_run_no_processor_list(lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE_ = jitted_run_processor_list(lowercase__ , lowercase__ , lowercase__ ) # scores should be equal self.assertTrue(jnp.allclose(lowercase__ , lowercase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
702
"""simple docstring""" import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def _lowerCamelCase ( __a ): # picklable for multiprocessing return x.sum() def _lowerCamelCase ( __a ): # picklable for multiprocessing return i + 1 @dataclass class snake_case : UpperCAmelCase__ = 42 UpperCAmelCase__ = 42 class snake_case ( __lowercase ): def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = [1, 2] SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': [1, 2], '''b''': [3, 4]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 1}, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = [2, 3] SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': [2, 3], '''b''': [4, 5]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''1''': 2}, '''b''': 3} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = 2 self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = {'''a''': np.eye(2 ), '''b''': np.zeros(3 ), '''c''': np.ones(2 )} SCREAMING_SNAKE_CASE_ = {'''a''': 2, '''b''': 0, '''c''': 2} SCREAMING_SNAKE_CASE_ = { '''a''': np.eye(2 ).astype(SCREAMING_SNAKE_CASE_ ), '''b''': np.zeros(3 ).astype(SCREAMING_SNAKE_CASE_ ), '''c''': np.ones(2 ).astype(SCREAMING_SNAKE_CASE_ ), } self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual( {k: v.tolist() for k, v in map_nested(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , map_numpy=SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): # can't pickle a local lambda map_nested(lambda SCREAMING_SNAKE_CASE_ : x + 1 , SCREAMING_SNAKE_CASE_ , num_proc=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = {'''a''': 1, '''b''': 2} SCREAMING_SNAKE_CASE_ = {'''a''': 3, '''b''': 4} SCREAMING_SNAKE_CASE_ = {'''a''': 5, '''b''': 6} SCREAMING_SNAKE_CASE_ = sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" class snake_case : UpperCAmelCase__ = '''bar''' SCREAMING_SNAKE_CASE_ = Foo() self.assertEqual(foo.my_attr , '''bar''' ) with temporary_assignment(SCREAMING_SNAKE_CASE_ , '''my_attr''' , '''BAR''' ): self.assertEqual(foo.my_attr , '''BAR''' ) self.assertEqual(foo.my_attr , '''bar''' ) @pytest.mark.parametrize( '''iterable_length, num_proc, expected_num_proc''', [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ], ) def _lowerCamelCase ( __a, __a, __a ): with patch('''datasets.utils.py_utils._single_map_nested''' ) as mock_single_map_nested, patch( '''datasets.parallel.parallel.Pool''' ) as mock_multiprocessing_pool: SCREAMING_SNAKE_CASE_ = {F'{i}': i for i in range(__a )} SCREAMING_SNAKE_CASE_ = map_nested(lambda __a : x + 10, __a, num_proc=__a, parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class snake_case ( __lowercase ): @require_tf def _lowercase (self ): """simple docstring""" import tensorflow as tf from tensorflow.keras import layers SCREAMING_SNAKE_CASE_ = layers.Dense(2 ) def gen_random_output(): SCREAMING_SNAKE_CASE_ = tf.random.uniform((1, 3) ) return model(SCREAMING_SNAKE_CASE_ ).numpy() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_tensorflow=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def _lowercase (self ): """simple docstring""" import torch def gen_random_output(): SCREAMING_SNAKE_CASE_ = torch.nn.Linear(3 , 2 ) SCREAMING_SNAKE_CASE_ = torch.rand(1 , 3 ) return model(SCREAMING_SNAKE_CASE_ ).detach().numpy() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_pytorch=SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def _lowercase (self ): """simple docstring""" def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize('''input_data''', [{}] ) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).data assert output_data == input_data @pytest.mark.parametrize( '''data, expected_output''', [ ({}, []), ([], []), ('''foo''', ['''foo''']), (['''foo''', '''bar'''], ['''foo''', '''bar''']), ([['''foo''', '''bar''']], ['''foo''', '''bar''']), ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']), ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']), ({'''a''': 1, '''b''': 2}, [1, 2]), ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]), ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]), ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]), ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]), ], ) def _lowerCamelCase ( __a, __a ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__a ).flatten() assert output == expected_output def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = A(x=1, y='''foobar''' ) SCREAMING_SNAKE_CASE_ = {'''x''': 1, '''y''': '''foobar'''} assert asdict(__a ) == expected_output SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': A(x=10, y='''foo''' )}, '''c''': [A(x=20, y='''bar''' )]} SCREAMING_SNAKE_CASE_ = {'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]} assert asdict(__a ) == expected_output with pytest.raises(__a ): asdict([1, A(x=10, y='''foo''' )] ) def _lowerCamelCase ( __a ): return text.split() def _lowerCamelCase ( __a ): yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def _lowerCamelCase ( ): with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__a, _split_text, kwargs_iterable=[{'''text''': '''hello there'''}] * 10 ) ) assert out.count('''hello''' ) == 10 assert out.count('''there''' ) == 10 assert len(__a ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = [] for yield_time, content in iflatmap_unordered( __a, _aseconds_generator_of_aitems_with_timing, kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__a ) assert out.count('''a''' ) == 2 assert out.count('''b''' ) == 2 assert len(__a ) == 4
628
0
import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class snake_case ( __lowercase ): UpperCAmelCase__ = (EulerDiscreteScheduler,) UpperCAmelCase__ = 10 def _lowercase (self , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = { 'num_train_timesteps': 11_00, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**SCREAMING_SNAKE_CASE_ ) return config def _lowercase (self ): """simple docstring""" for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] , [0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE_ , beta_end=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE_ ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = self.dummy_model() SCREAMING_SNAKE_CASE_ = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE_ = sample.to(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE_ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = output.prev_sample SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 10.08_07 ) < 1e-2 assert abs(result_mean.item() - 0.01_31 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config(prediction_type='''v_prediction''' ) SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = self.dummy_model() SCREAMING_SNAKE_CASE_ = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE_ = sample.to(SCREAMING_SNAKE_CASE_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE_ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = output.prev_sample SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 0.00_02 ) < 1e-2 assert abs(result_mean.item() - 2.2_6_7_6e-0_6 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = self.dummy_model() SCREAMING_SNAKE_CASE_ = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() SCREAMING_SNAKE_CASE_ = sample.to(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = output.prev_sample SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 10.08_07 ) < 1e-2 assert abs(result_mean.item() - 0.01_31 ) < 1e-3 def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ = scheduler_class(**SCREAMING_SNAKE_CASE_ , use_karras_sigmas=SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE_ = self.dummy_model() SCREAMING_SNAKE_CASE_ = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() SCREAMING_SNAKE_CASE_ = sample.to(SCREAMING_SNAKE_CASE_ ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE_ = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = output.prev_sample SCREAMING_SNAKE_CASE_ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE_ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 1_24.52_29_94_99_51_17_19 ) < 1e-2 assert abs(result_mean.item() - 0.1_62_13_93_26_33_39_99_63 ) < 1e-3
703
"""simple docstring""" import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCAmelCase__ = { 'facebook/maskformer-swin-base-ade': ( 'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowerCAmelCase__ = logging.get_logger(__name__) class snake_case ( __lowercase ): UpperCAmelCase__ = '''maskformer''' UpperCAmelCase__ = {'''hidden_size''': '''mask_feature_size'''} UpperCAmelCase__ = ['''resnet''', '''swin'''] UpperCAmelCase__ = ['''detr'''] def __init__(self , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0.02 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = 20.0 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k SCREAMING_SNAKE_CASE_ = SwinConfig( image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = backbone_config.pop('''model_type''' ) SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ' f'Supported model types: {",".join(self.backbones_supported )}' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 SCREAMING_SNAKE_CASE_ = DetrConfig() else: # verify that the decoder is supported SCREAMING_SNAKE_CASE_ = ( decoder_config.pop('''model_type''' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'Transformer Decoder {decoder_type} not supported, please use one of' f' {",".join(self.decoders_supported )}' ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[decoder_type] SCREAMING_SNAKE_CASE_ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE_ = backbone_config SCREAMING_SNAKE_CASE_ = decoder_config # main feature dimension for the model SCREAMING_SNAKE_CASE_ = fpn_feature_size SCREAMING_SNAKE_CASE_ = mask_feature_size # initializer SCREAMING_SNAKE_CASE_ = init_std SCREAMING_SNAKE_CASE_ = init_xavier_std # Hungarian matcher && loss SCREAMING_SNAKE_CASE_ = cross_entropy_weight SCREAMING_SNAKE_CASE_ = dice_weight SCREAMING_SNAKE_CASE_ = mask_weight SCREAMING_SNAKE_CASE_ = use_auxiliary_loss SCREAMING_SNAKE_CASE_ = no_object_weight SCREAMING_SNAKE_CASE_ = output_auxiliary_logits SCREAMING_SNAKE_CASE_ = self.decoder_config.encoder_attention_heads SCREAMING_SNAKE_CASE_ = self.decoder_config.num_hidden_layers super().__init__(**SCREAMING_SNAKE_CASE_ ) @classmethod def _lowercase (cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): """simple docstring""" return cls( backbone_config=SCREAMING_SNAKE_CASE_ , decoder_config=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def _lowercase (self ): """simple docstring""" SCREAMING_SNAKE_CASE_ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE_ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE_ = self.decoder_config.to_dict() SCREAMING_SNAKE_CASE_ = self.__class__.model_type return output
628
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available lowerCAmelCase__ = {'tokenization_herbert': ['HerbertTokenizer']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['HerbertTokenizerFast'] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
704
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False SCREAMING_SNAKE_CASE_ = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] SCREAMING_SNAKE_CASE_ = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE_ = [4, 4, 4, 4] SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE_ = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE_ = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE_ = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE_ = 128 elif "large" in model_name: SCREAMING_SNAKE_CASE_ = 192 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE_ = 256 elif "huge" in model_name: SCREAMING_SNAKE_CASE_ = 352 # set label information SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE_ = '''imagenet-22k-id2label.json''' else: SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(__a, __a, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = FocalNetConfig( embed_dim=__a, depths=__a, focal_levels=__a, focal_windows=__a, use_conv_embed=__a, idalabel=__a, labelaid=__a, use_post_layernorm=__a, use_layerscale=__a, ) return config def _lowerCamelCase ( __a ): 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 "layers" in name: SCREAMING_SNAKE_CASE_ = '''encoder.''' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE_ = name.replace('''encoder.layers''', '''encoder.stages''' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('''downsample.proj''', '''downsample.projection''' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ = name.replace('''blocks''', '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.f''', '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.h''', '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE_ = name.replace('''modulation.proj''', '''modulation.projection_out''' ) if name == "norm.weight": SCREAMING_SNAKE_CASE_ = '''layernorm.weight''' if name == "norm.bias": SCREAMING_SNAKE_CASE_ = '''layernorm.bias''' if "head" in name: SCREAMING_SNAKE_CASE_ = name.replace('''head''', '''classifier''' ) else: SCREAMING_SNAKE_CASE_ = '''focalnet.''' + name return name def _lowerCamelCase ( __a, __a, __a=False ): # fmt: off SCREAMING_SNAKE_CASE_ = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on SCREAMING_SNAKE_CASE_ = model_name_to_url[model_name] print('''Checkpoint URL: ''', __a ) SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(__a, map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ = val SCREAMING_SNAKE_CASE_ = get_focalnet_config(__a ) SCREAMING_SNAKE_CASE_ = FocalNetForImageClassification(__a ) model.eval() # load state dict model.load_state_dict(__a ) # verify conversion SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = BitImageProcessor( do_resize=__a, size={'''shortest_edge''': 256}, resample=PILImageResampling.BILINEAR, do_center_crop=__a, crop_size=224, do_normalize=__a, image_mean=__a, image_std=__a, ) SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__a, stream=__a ).raw ) SCREAMING_SNAKE_CASE_ = processor(images=__a, return_tensors='''pt''' ) SCREAMING_SNAKE_CASE_ = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6], std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) SCREAMING_SNAKE_CASE_ = image_transforms(__a ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values, __a, atol=1E-4 ) SCREAMING_SNAKE_CASE_ = model(**__a ) SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(-1 ).item() print('''Predicted class:''', model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''', outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE_ = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE_ = torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE_ = torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE_ = torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8] ) assert torch.allclose(outputs.logits[0, :3], __a, atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model and processor of {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if push_to_hub: print(F'Pushing model and processor of {model_name} to the hub...' ) model.push_to_hub(F'{model_name}' ) processor.push_to_hub(F'{model_name}' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
628
0