code stringlengths 82 53.2k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_url
from PIL import Image
from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase = logging.get_logger(__name__)
def _A ( lowerCAmelCase_ : str ):
"""simple docstring"""
lowerCAmelCase__ = DPTConfig(embedding_type="hybrid" )
if "large" in checkpoint_url:
lowerCAmelCase__ = 1024
lowerCAmelCase__ = 4096
lowerCAmelCase__ = 24
lowerCAmelCase__ = 16
lowerCAmelCase__ = [5, 11, 17, 23]
lowerCAmelCase__ = [256, 512, 1024, 1024]
lowerCAmelCase__ = (1, 384, 384)
if "nyu" or "midas" in checkpoint_url:
lowerCAmelCase__ = 768
lowerCAmelCase__ = [1, 1, 1, 0.5]
lowerCAmelCase__ = [256, 512, 768, 768]
lowerCAmelCase__ = 150
lowerCAmelCase__ = 16
lowerCAmelCase__ = (1, 384, 384)
lowerCAmelCase__ = False
lowerCAmelCase__ = "project"
if "ade" in checkpoint_url:
lowerCAmelCase__ = True
lowerCAmelCase__ = 768
lowerCAmelCase__ = [1, 1, 1, 0.5]
lowerCAmelCase__ = 150
lowerCAmelCase__ = 16
lowerCAmelCase__ = "huggingface/label-files"
lowerCAmelCase__ = "ade20k-id2label.json"
lowerCAmelCase__ = json.load(open(cached_download(hf_hub_url(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) ) , "r" ) )
lowerCAmelCase__ = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()}
lowerCAmelCase__ = idalabel
lowerCAmelCase__ = {v: k for k, v in idalabel.items()}
lowerCAmelCase__ = [1, 150, 480, 480]
return config, expected_shape
def _A ( lowerCAmelCase_ : List[Any] ):
"""simple docstring"""
lowerCAmelCase__ = ["pretrained.model.head.weight", "pretrained.model.head.bias"]
for k in ignore_keys:
state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ )
def _A ( lowerCAmelCase_ : Optional[int] ):
"""simple docstring"""
if (
"pretrained.model" in name
and "cls_token" not in name
and "pos_embed" not in name
and "patch_embed" not in name
):
lowerCAmelCase__ = name.replace("pretrained.model" , "dpt.encoder" )
if "pretrained.model" in name:
lowerCAmelCase__ = name.replace("pretrained.model" , "dpt.embeddings" )
if "patch_embed" in name:
lowerCAmelCase__ = name.replace("patch_embed" , "" )
if "pos_embed" in name:
lowerCAmelCase__ = name.replace("pos_embed" , "position_embeddings" )
if "attn.proj" in name:
lowerCAmelCase__ = name.replace("attn.proj" , "attention.output.dense" )
if "proj" in name and "project" not in name:
lowerCAmelCase__ = name.replace("proj" , "projection" )
if "blocks" in name:
lowerCAmelCase__ = name.replace("blocks" , "layer" )
if "mlp.fc1" in name:
lowerCAmelCase__ = name.replace("mlp.fc1" , "intermediate.dense" )
if "mlp.fc2" in name:
lowerCAmelCase__ = name.replace("mlp.fc2" , "output.dense" )
if "norm1" in name and "backbone" not in name:
lowerCAmelCase__ = name.replace("norm1" , "layernorm_before" )
if "norm2" in name and "backbone" not in name:
lowerCAmelCase__ = name.replace("norm2" , "layernorm_after" )
if "scratch.output_conv" in name:
lowerCAmelCase__ = name.replace("scratch.output_conv" , "head" )
if "scratch" in name:
lowerCAmelCase__ = name.replace("scratch" , "neck" )
if "layer1_rn" in name:
lowerCAmelCase__ = name.replace("layer1_rn" , "convs.0" )
if "layer2_rn" in name:
lowerCAmelCase__ = name.replace("layer2_rn" , "convs.1" )
if "layer3_rn" in name:
lowerCAmelCase__ = name.replace("layer3_rn" , "convs.2" )
if "layer4_rn" in name:
lowerCAmelCase__ = name.replace("layer4_rn" , "convs.3" )
if "refinenet" in name:
lowerCAmelCase__ = int(name[len("neck.refinenet" ) : len("neck.refinenet" ) + 1] )
# tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
lowerCAmelCase__ = name.replace(F'refinenet{layer_idx}' , F'fusion_stage.layers.{abs(layer_idx-4 )}' )
if "out_conv" in name:
lowerCAmelCase__ = name.replace("out_conv" , "projection" )
if "resConfUnit1" in name:
lowerCAmelCase__ = name.replace("resConfUnit1" , "residual_layer1" )
if "resConfUnit2" in name:
lowerCAmelCase__ = name.replace("resConfUnit2" , "residual_layer2" )
if "conv1" in name:
lowerCAmelCase__ = name.replace("conv1" , "convolution1" )
if "conv2" in name:
lowerCAmelCase__ = name.replace("conv2" , "convolution2" )
# readout blocks
if "pretrained.act_postprocess1.0.project.0" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess1.0.project.0" , "neck.reassemble_stage.readout_projects.0.0" )
if "pretrained.act_postprocess2.0.project.0" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess2.0.project.0" , "neck.reassemble_stage.readout_projects.1.0" )
if "pretrained.act_postprocess3.0.project.0" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess3.0.project.0" , "neck.reassemble_stage.readout_projects.2.0" )
if "pretrained.act_postprocess4.0.project.0" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess4.0.project.0" , "neck.reassemble_stage.readout_projects.3.0" )
# resize blocks
if "pretrained.act_postprocess1.3" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess1.3" , "neck.reassemble_stage.layers.0.projection" )
if "pretrained.act_postprocess1.4" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess1.4" , "neck.reassemble_stage.layers.0.resize" )
if "pretrained.act_postprocess2.3" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess2.3" , "neck.reassemble_stage.layers.1.projection" )
if "pretrained.act_postprocess2.4" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess2.4" , "neck.reassemble_stage.layers.1.resize" )
if "pretrained.act_postprocess3.3" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess3.3" , "neck.reassemble_stage.layers.2.projection" )
if "pretrained.act_postprocess4.3" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess4.3" , "neck.reassemble_stage.layers.3.projection" )
if "pretrained.act_postprocess4.4" in name:
lowerCAmelCase__ = name.replace("pretrained.act_postprocess4.4" , "neck.reassemble_stage.layers.3.resize" )
if "pretrained" in name:
lowerCAmelCase__ = name.replace("pretrained" , "dpt" )
if "bn" in name:
lowerCAmelCase__ = name.replace("bn" , "batch_norm" )
if "head" in name:
lowerCAmelCase__ = name.replace("head" , "head.head" )
if "encoder.norm" in name:
lowerCAmelCase__ = name.replace("encoder.norm" , "layernorm" )
if "auxlayer" in name:
lowerCAmelCase__ = name.replace("auxlayer" , "auxiliary_head.head" )
if "backbone" in name:
lowerCAmelCase__ = name.replace("backbone" , "backbone.bit.encoder" )
if ".." in name:
lowerCAmelCase__ = name.replace(".." , "." )
if "stem.conv" in name:
lowerCAmelCase__ = name.replace("stem.conv" , "bit.embedder.convolution" )
if "blocks" in name:
lowerCAmelCase__ = name.replace("blocks" , "layers" )
if "convolution" in name and "backbone" in name:
lowerCAmelCase__ = name.replace("convolution" , "conv" )
if "layer" in name and "backbone" in name:
lowerCAmelCase__ = name.replace("layer" , "layers" )
if "backbone.bit.encoder.bit" in name:
lowerCAmelCase__ = name.replace("backbone.bit.encoder.bit" , "backbone.bit" )
if "embedder.conv" in name:
lowerCAmelCase__ = name.replace("embedder.conv" , "embedder.convolution" )
if "backbone.bit.encoder.stem.norm" in name:
lowerCAmelCase__ = name.replace("backbone.bit.encoder.stem.norm" , "backbone.bit.embedder.norm" )
return name
def _A ( lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[Any] ):
"""simple docstring"""
for i in range(config.num_hidden_layers ):
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
lowerCAmelCase__ = state_dict.pop(F'dpt.encoder.layer.{i}.attn.qkv.weight' )
lowerCAmelCase__ = state_dict.pop(F'dpt.encoder.layer.{i}.attn.qkv.bias' )
# next, add query, keys and values (in that order) to the state dict
lowerCAmelCase__ = in_proj_weight[: config.hidden_size, :]
lowerCAmelCase__ = in_proj_bias[: config.hidden_size]
lowerCAmelCase__ = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
lowerCAmelCase__ = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
lowerCAmelCase__ = in_proj_weight[
-config.hidden_size :, :
]
lowerCAmelCase__ = in_proj_bias[-config.hidden_size :]
def _A ( ):
"""simple docstring"""
lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg"
lowerCAmelCase__ = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw )
return im
@torch.no_grad()
def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Any , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[str] ):
"""simple docstring"""
lowerCAmelCase__ , lowerCAmelCase__ = get_dpt_config(lowerCAmelCase_ )
# load original state_dict from URL
# state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
lowerCAmelCase__ = torch.load(lowerCAmelCase_ , map_location="cpu" )
# remove certain keys
remove_ignore_keys_(lowerCAmelCase_ )
# rename keys
for key in state_dict.copy().keys():
lowerCAmelCase__ = state_dict.pop(lowerCAmelCase_ )
lowerCAmelCase__ = val
# read in qkv matrices
read_in_q_k_v(lowerCAmelCase_ , lowerCAmelCase_ )
# load HuggingFace model
lowerCAmelCase__ = DPTForSemanticSegmentation(lowerCAmelCase_ ) if "ade" in checkpoint_url else DPTForDepthEstimation(lowerCAmelCase_ )
model.load_state_dict(lowerCAmelCase_ )
model.eval()
# Check outputs on an image
lowerCAmelCase__ = 480 if "ade" in checkpoint_url else 384
lowerCAmelCase__ = DPTImageProcessor(size=lowerCAmelCase_ )
lowerCAmelCase__ = prepare_img()
lowerCAmelCase__ = image_processor(lowerCAmelCase_ , return_tensors="pt" )
# forward pass
lowerCAmelCase__ = model(**lowerCAmelCase_ ).logits if "ade" in checkpoint_url else model(**lowerCAmelCase_ ).predicted_depth
if show_prediction:
lowerCAmelCase__ = (
torch.nn.functional.interpolate(
outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode="bicubic" , align_corners=lowerCAmelCase_ , )
.squeeze()
.cpu()
.numpy()
)
Image.fromarray((prediction / prediction.max()) * 255 ).show()
if pytorch_dump_folder_path is not None:
Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ )
print(F'Saving model to {pytorch_dump_folder_path}' )
model.save_pretrained(lowerCAmelCase_ )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(lowerCAmelCase_ )
if push_to_hub:
model.push_to_hub("ybelkada/dpt-hybrid-midas" )
image_processor.push_to_hub("ybelkada/dpt-hybrid-midas" )
if __name__ == "__main__":
UpperCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--checkpoint_url',
default='https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt',
type=str,
help='URL of the original DPT checkpoint you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
required=False,
help='Path to the output PyTorch model directory.',
)
parser.add_argument(
'--push_to_hub',
action='store_true',
)
parser.add_argument(
'--model_name',
default='dpt-large',
type=str,
help='Name of the model, in case you\'re pushing to the hub.',
)
parser.add_argument(
'--show_prediction',
action='store_true',
)
UpperCamelCase = parser.parse_args()
convert_dpt_checkpoint(
args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction
)
| 61 |
import unittest
from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model')
@require_sentencepiece
@require_tokenizers
class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ):
"""simple docstring"""
snake_case__ = XLNetTokenizer
snake_case__ = XLNetTokenizerFast
snake_case__ = True
snake_case__ = True
def a ( self : str ) -> str:
super().setUp()
# We have a SentencePiece fixture for testing
lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ )
tokenizer.sanitize_special_tokens()
tokenizer.save_pretrained(self.tmpdirname )
def a ( self : List[str] ) -> List[Any]:
lowerCAmelCase__ = "<s>"
lowerCAmelCase__ = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ )
def a ( self : Union[str, Any] ) -> str:
lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "<eod>" )
self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 )
def a ( self : int ) -> Dict:
self.assertEqual(self.get_tokenizer().vocab_size , 1_000 )
def a ( self : List[str] ) -> Any:
lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = tokenizer.tokenize("This is a test" )
self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] )
lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." )
self.assertListEqual(
SCREAMING_SNAKE_CASE__ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"9",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"é",
".",
] , )
lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] )
lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ )
self.assertListEqual(
SCREAMING_SNAKE_CASE__ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"<unk>",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"<unk>",
".",
] , )
def a ( self : Optional[int] ) -> Optional[Any]:
lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." )
self.assertListEqual(
SCREAMING_SNAKE_CASE__ , [
SPIECE_UNDERLINE + "",
"i",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"9",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"se",
".",
] , )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] )
def a ( self : List[Any] ) -> Optional[int]:
lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." )
self.assertListEqual(
SCREAMING_SNAKE_CASE__ , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"9",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"se",
".",
] , )
@slow
def a ( self : Any ) -> Any:
lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" )
lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
assert encoded_sentence == text + [4, 3]
assert encoded_pair == text + [4] + text_a + [4, 3]
@slow
def a ( self : Union[str, Any] ) -> Any:
# fmt: off
lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
| 61 | 1 |
from typing import Optional, Union
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig
lowercase_ = logging.get_logger(__name__)
# General docstring
lowercase_ = 'MobileNetV1Config'
# Base docstring
lowercase_ = 'google/mobilenet_v1_1.0_224'
lowercase_ = [1, 1_0_2_4, 7, 7]
# Image classification docstring
lowercase_ = 'google/mobilenet_v1_1.0_224'
lowercase_ = 'tabby, tabby cat'
lowercase_ = [
'google/mobilenet_v1_1.0_224',
'google/mobilenet_v1_0.75_192',
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ):
__lowerCamelCase : int = {}
if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
__lowerCamelCase : List[str] = model.mobilenet_va
else:
__lowerCamelCase : Any = model
__lowerCamelCase : Dict = 'MobilenetV1/Conv2d_0/'
__lowerCamelCase : Any = backbone.conv_stem.convolution.weight
__lowerCamelCase : Union[str, Any] = backbone.conv_stem.normalization.bias
__lowerCamelCase : Optional[Any] = backbone.conv_stem.normalization.weight
__lowerCamelCase : Union[str, Any] = backbone.conv_stem.normalization.running_mean
__lowerCamelCase : int = backbone.conv_stem.normalization.running_var
for i in range(13 ):
__lowerCamelCase : Union[str, Any] = i + 1
__lowerCamelCase : Optional[Any] = i * 2
__lowerCamelCase : Any = backbone.layer[pt_index]
__lowerCamelCase : Optional[int] = f'MobilenetV1/Conv2d_{tf_index}_depthwise/'
__lowerCamelCase : Optional[Any] = pointer.convolution.weight
__lowerCamelCase : Any = pointer.normalization.bias
__lowerCamelCase : Optional[int] = pointer.normalization.weight
__lowerCamelCase : Optional[Any] = pointer.normalization.running_mean
__lowerCamelCase : Optional[int] = pointer.normalization.running_var
__lowerCamelCase : List[Any] = backbone.layer[pt_index + 1]
__lowerCamelCase : Optional[int] = f'MobilenetV1/Conv2d_{tf_index}_pointwise/'
__lowerCamelCase : Any = pointer.convolution.weight
__lowerCamelCase : Optional[Any] = pointer.normalization.bias
__lowerCamelCase : Any = pointer.normalization.weight
__lowerCamelCase : str = pointer.normalization.running_mean
__lowerCamelCase : List[Any] = pointer.normalization.running_var
if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
__lowerCamelCase : List[Any] = 'MobilenetV1/Logits/Conv2d_1c_1x1/'
__lowerCamelCase : List[Any] = model.classifier.weight
__lowerCamelCase : str = model.classifier.bias
return tf_to_pt_map
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
try:
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '
'https://www.tensorflow.org/install/ for installation instructions.' )
raise
# Load weights from TF model
__lowerCamelCase : Any = tf.train.list_variables(SCREAMING_SNAKE_CASE__ )
__lowerCamelCase : Dict = {}
for name, shape in init_vars:
logger.info(f'Loading TF weight {name} with shape {shape}' )
__lowerCamelCase : str = tf.train.load_variable(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
__lowerCamelCase : Any = array
# Build TF to PyTorch weights loading map
__lowerCamelCase : Optional[int] = _build_tf_to_pytorch_map(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
for name, pointer in tf_to_pt_map.items():
logger.info(f'Importing {name}' )
if name not in tf_weights:
logger.info(f'{name} not in tf pre-trained weights, skipping' )
continue
__lowerCamelCase : Any = tf_weights[name]
if "depthwise_weights" in name:
logger.info('Transposing depthwise' )
__lowerCamelCase : List[str] = np.transpose(SCREAMING_SNAKE_CASE__ , (2, 3, 0, 1) )
elif "weights" in name:
logger.info('Transposing' )
if len(pointer.shape ) == 2: # copying into linear layer
__lowerCamelCase : Optional[Any] = array.squeeze().transpose()
else:
__lowerCamelCase : Tuple = np.transpose(SCREAMING_SNAKE_CASE__ , (3, 2, 0, 1) )
if pointer.shape != array.shape:
raise ValueError(f'Pointer shape {pointer.shape} and array shape {array.shape} mismatched' )
logger.info(f'Initialize PyTorch weight {name} {array.shape}' )
__lowerCamelCase : Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ )
tf_weights.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
tf_weights.pop(name + '/RMSProp' , SCREAMING_SNAKE_CASE__ )
tf_weights.pop(name + '/RMSProp_1' , SCREAMING_SNAKE_CASE__ )
tf_weights.pop(name + '/ExponentialMovingAverage' , SCREAMING_SNAKE_CASE__ )
logger.info(f'Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}' )
return model
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
__lowerCamelCase : List[Any] = features.shape[-2:]
__lowerCamelCase : List[Any] = conv_layer.stride
__lowerCamelCase : Any = conv_layer.kernel_size
if in_height % stride_height == 0:
__lowerCamelCase : Dict = max(kernel_height - stride_height , 0 )
else:
__lowerCamelCase : Union[str, Any] = max(kernel_height - (in_height % stride_height) , 0 )
if in_width % stride_width == 0:
__lowerCamelCase : List[Any] = max(kernel_width - stride_width , 0 )
else:
__lowerCamelCase : Optional[Any] = max(kernel_width - (in_width % stride_width) , 0 )
__lowerCamelCase : Any = pad_along_width // 2
__lowerCamelCase : Optional[Any] = pad_along_width - pad_left
__lowerCamelCase : Any = pad_along_height // 2
__lowerCamelCase : int = pad_along_height - pad_top
__lowerCamelCase : Dict = (pad_left, pad_right, pad_top, pad_bottom)
return nn.functional.pad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , 0.0 )
class A_ ( nn.Module ):
'''simple docstring'''
def __init__( self: int , a: MobileNetVaConfig , a: int , a: int , a: int , a: Optional[int] = 1 , a: Optional[int] = 1 , a: bool = False , a: Optional[bool] = True , a: Optional[bool or str] = True , ):
super().__init__()
__lowerCamelCase : int = config
if in_channels % groups != 0:
raise ValueError(F'Input channels ({in_channels}) are not divisible by {groups} groups.' )
if out_channels % groups != 0:
raise ValueError(F'Output channels ({out_channels}) are not divisible by {groups} groups.' )
__lowerCamelCase : List[Any] = 0 if config.tf_padding else int((kernel_size - 1) / 2 )
__lowerCamelCase : List[Any] = nn.Convad(
in_channels=a , out_channels=a , kernel_size=a , stride=a , padding=a , groups=a , bias=a , padding_mode='zeros' , )
if use_normalization:
__lowerCamelCase : List[Any] = nn.BatchNormad(
num_features=a , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=a , track_running_stats=a , )
else:
__lowerCamelCase : Any = None
if use_activation:
if isinstance(a , a ):
__lowerCamelCase : Tuple = ACTaFN[use_activation]
elif isinstance(config.hidden_act , a ):
__lowerCamelCase : Any = ACTaFN[config.hidden_act]
else:
__lowerCamelCase : Dict = config.hidden_act
else:
__lowerCamelCase : Dict = None
def _snake_case ( self: Dict , a: torch.Tensor ):
if self.config.tf_padding:
__lowerCamelCase : Tuple = apply_tf_padding(a , self.convolution )
__lowerCamelCase : List[Any] = self.convolution(a )
if self.normalization is not None:
__lowerCamelCase : List[Any] = self.normalization(a )
if self.activation is not None:
__lowerCamelCase : List[Any] = self.activation(a )
return features
class A_ ( __UpperCamelCase ):
'''simple docstring'''
__snake_case = MobileNetVaConfig
__snake_case = load_tf_weights_in_mobilenet_va
__snake_case = """mobilenet_v1"""
__snake_case = """pixel_values"""
__snake_case = False
def _snake_case ( self: Optional[Any] , a: Union[nn.Linear, nn.Convad] ):
if isinstance(a , (nn.Linear, nn.Convad) ):
module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range )
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(a , nn.BatchNormad ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
lowercase_ = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'
lowercase_ = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'
@add_start_docstrings(
"""The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.""" , __UpperCamelCase , )
class A_ ( __UpperCamelCase ):
'''simple docstring'''
def __init__( self: Optional[int] , a: MobileNetVaConfig , a: bool = True ):
super().__init__(a )
__lowerCamelCase : Union[str, Any] = config
__lowerCamelCase : int = 32
__lowerCamelCase : Dict = max(int(depth * config.depth_multiplier ) , config.min_depth )
__lowerCamelCase : Optional[int] = MobileNetVaConvLayer(
a , in_channels=config.num_channels , out_channels=a , kernel_size=3 , stride=2 , )
__lowerCamelCase : Tuple = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]
__lowerCamelCase : Dict = nn.ModuleList()
for i in range(13 ):
__lowerCamelCase : int = out_channels
if strides[i] == 2 or i == 0:
depth *= 2
__lowerCamelCase : Optional[int] = max(int(depth * config.depth_multiplier ) , config.min_depth )
self.layer.append(
MobileNetVaConvLayer(
a , in_channels=a , out_channels=a , kernel_size=3 , stride=strides[i] , groups=a , ) )
self.layer.append(
MobileNetVaConvLayer(
a , in_channels=a , out_channels=a , kernel_size=1 , ) )
__lowerCamelCase : str = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def _snake_case ( self: List[str] , a: Dict ):
raise NotImplementedError
@add_start_docstrings_to_model_forward(a )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def _snake_case ( self: Any , a: Optional[torch.Tensor] = None , a: Optional[bool] = None , a: Optional[bool] = None , ):
__lowerCamelCase : Optional[int] = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
__lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError('You have to specify pixel_values' )
__lowerCamelCase : Union[str, Any] = self.conv_stem(a )
__lowerCamelCase : List[Any] = () if output_hidden_states else None
for i, layer_module in enumerate(self.layer ):
__lowerCamelCase : Optional[Any] = layer_module(a )
if output_hidden_states:
__lowerCamelCase : Tuple = all_hidden_states + (hidden_states,)
__lowerCamelCase : Optional[int] = hidden_states
if self.pooler is not None:
__lowerCamelCase : str = torch.flatten(self.pooler(a ) , start_dim=1 )
else:
__lowerCamelCase : Tuple = None
if not return_dict:
return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None )
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=a , pooler_output=a , hidden_states=a , )
@add_start_docstrings(
"""
MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
ImageNet.
""" , __UpperCamelCase , )
class A_ ( __UpperCamelCase ):
'''simple docstring'''
def __init__( self: Optional[Any] , a: MobileNetVaConfig ):
super().__init__(a )
__lowerCamelCase : Any = config.num_labels
__lowerCamelCase : Optional[Any] = MobileNetVaModel(a )
__lowerCamelCase : str = self.mobilenet_va.layer[-1].convolution.out_channels
# Classifier head
__lowerCamelCase : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=a )
__lowerCamelCase : int = nn.Linear(a , config.num_labels ) if config.num_labels > 0 else nn.Identity()
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(a )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def _snake_case ( self: int , a: Optional[torch.Tensor] = None , a: Optional[bool] = None , a: Optional[torch.Tensor] = None , a: Optional[bool] = None , ):
__lowerCamelCase : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict
__lowerCamelCase : Optional[Any] = self.mobilenet_va(a , output_hidden_states=a , return_dict=a )
__lowerCamelCase : Tuple = outputs.pooler_output if return_dict else outputs[1]
__lowerCamelCase : List[Any] = self.classifier(self.dropout(a ) )
__lowerCamelCase : List[Any] = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
__lowerCamelCase : List[Any] = 'regression'
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
__lowerCamelCase : List[Any] = 'single_label_classification'
else:
__lowerCamelCase : str = 'multi_label_classification'
if self.config.problem_type == "regression":
__lowerCamelCase : str = MSELoss()
if self.num_labels == 1:
__lowerCamelCase : Optional[int] = loss_fct(logits.squeeze() , labels.squeeze() )
else:
__lowerCamelCase : Optional[int] = loss_fct(a , a )
elif self.config.problem_type == "single_label_classification":
__lowerCamelCase : Optional[int] = CrossEntropyLoss()
__lowerCamelCase : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
__lowerCamelCase : int = BCEWithLogitsLoss()
__lowerCamelCase : List[Any] = loss_fct(a , a )
if not return_dict:
__lowerCamelCase : int = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(
loss=a , logits=a , hidden_states=outputs.hidden_states , )
| 706 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
lowercase_ = {'configuration_opt': ['OPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OPTConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ = [
'OPT_PRETRAINED_MODEL_ARCHIVE_LIST',
'OPTForCausalLM',
'OPTModel',
'OPTPreTrainedModel',
'OPTForSequenceClassification',
'OPTForQuestionAnswering',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ = ['TFOPTForCausalLM', 'TFOPTModel', 'TFOPTPreTrainedModel']
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ = [
'FlaxOPTForCausalLM',
'FlaxOPTModel',
'FlaxOPTPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_opt import (
OPT_PRETRAINED_MODEL_ARCHIVE_LIST,
OPTForCausalLM,
OPTForQuestionAnswering,
OPTForSequenceClassification,
OPTModel,
OPTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel
else:
import sys
lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 230 | 0 |
'''simple docstring'''
from transformers import DistilBertTokenizer, DistilBertTokenizerFast
from transformers.testing_utils import require_tokenizers, slow
from ..bert.test_tokenization_bert import BertTokenizationTest
@require_tokenizers
class __magic_name__ ( a_ ):
UpperCamelCase__ = DistilBertTokenizer
UpperCamelCase__ = DistilBertTokenizerFast
UpperCamelCase__ = True
@slow
def _A( self ):
lowercase =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' )
lowercase =tokenizer.encode('''sequence builders''' , add_special_tokens=_snake_case )
lowercase =tokenizer.encode('''multi-sequence build''' , add_special_tokens=_snake_case )
lowercase =tokenizer.build_inputs_with_special_tokens(_snake_case )
lowercase =tokenizer.build_inputs_with_special_tokens(_snake_case , _snake_case )
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
tokenizer.sep_token_id
]
| 72 |
'''simple docstring'''
import json
import os
import unittest
from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class lowerCAmelCase_ ( a_ , unittest.TestCase ):
__UpperCAmelCase = DebertaTokenizer
__UpperCAmelCase = True
__UpperCAmelCase = DebertaTokenizerFast
def __snake_case ( self : Dict ):
'''simple docstring'''
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
snake_case : List[Any] =[
'''l''',
'''o''',
'''w''',
'''e''',
'''r''',
'''s''',
'''t''',
'''i''',
'''d''',
'''n''',
'''\u0120''',
'''\u0120l''',
'''\u0120n''',
'''\u0120lo''',
'''\u0120low''',
'''er''',
'''\u0120lowest''',
'''\u0120newer''',
'''\u0120wider''',
'''[UNK]''',
]
snake_case : Dict =dict(zip(_snake_case, range(len(_snake_case ) ) ) )
snake_case : Tuple =['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
snake_case : List[Any] ={'''unk_token''': '''[UNK]'''}
snake_case : List[Any] =os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['''vocab_file'''] )
snake_case : Tuple =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(_snake_case ) + '''\n''' )
with open(self.merges_file, '''w''', encoding='''utf-8''' ) as fp:
fp.write('''\n'''.join(_snake_case ) )
def __snake_case ( self : str, **_snake_case : List[str] ):
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname, **_snake_case )
def __snake_case ( self : List[str], _snake_case : List[str] ):
'''simple docstring'''
snake_case : List[str] ='''lower newer'''
snake_case : Optional[int] ='''lower newer'''
return input_text, output_text
def __snake_case ( self : Any ):
'''simple docstring'''
snake_case : List[Any] =self.get_tokenizer()
snake_case : List[Any] ='''lower newer'''
snake_case : Union[str, Any] =['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
snake_case : str =tokenizer.tokenize(_snake_case )
self.assertListEqual(_snake_case, _snake_case )
snake_case : Any =tokens + [tokenizer.unk_token]
snake_case : List[Any] =[0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case ), _snake_case )
def __snake_case ( self : Tuple ):
'''simple docstring'''
snake_case : Optional[Any] =self.get_tokenizer()
snake_case : Any =tokenizer('''Hello''', '''World''' )
snake_case : List[Any] =[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
self.assertListEqual(tokd['''token_type_ids'''], _snake_case )
@slow
def __snake_case ( self : Optional[Any] ):
'''simple docstring'''
snake_case : int =self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' )
snake_case : List[Any] =tokenizer.encode('''sequence builders''', add_special_tokens=_snake_case )
snake_case : str =tokenizer.encode('''multi-sequence build''', add_special_tokens=_snake_case )
snake_case : Union[str, Any] =tokenizer.encode(
'''sequence builders''', add_special_tokens=_snake_case, add_prefix_space=_snake_case )
snake_case : Optional[int] =tokenizer.encode(
'''sequence builders''', '''multi-sequence build''', add_special_tokens=_snake_case, add_prefix_space=_snake_case )
snake_case : str =tokenizer.build_inputs_with_special_tokens(_snake_case )
snake_case : Tuple =tokenizer.build_inputs_with_special_tokens(_snake_case, _snake_case )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
@slow
def __snake_case ( self : Dict ):
'''simple docstring'''
snake_case : int =[self.tokenizer_class]
if self.test_rust_tokenizer:
tokenizer_classes.append(self.rust_tokenizer_class )
for tokenizer_class in tokenizer_classes:
snake_case : Optional[int] =tokenizer_class.from_pretrained('''microsoft/deberta-base''' )
snake_case : Optional[Any] =[
'''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''',
'''ALBERT incorporates two parameter reduction techniques''',
'''The first one is a factorized embedding parameterization. By decomposing the large vocabulary'''
''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'''
''' vocabulary embedding.''',
]
snake_case : int =tokenizer(_snake_case, padding=_snake_case )
snake_case : str =[tokenizer.decode(_snake_case, skip_special_tokens=_snake_case ) for seq in encoding['''input_ids''']]
# fmt: off
snake_case : Optional[Any] ={
'''input_ids''': [
[1, 2_118, 11_126, 565, 35, 83, 25_191, 163, 18_854, 13, 12_156, 12, 16_101, 25_376, 13_807, 9, 22_205, 27_893, 1_635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 2_118, 11_126, 565, 24_536, 80, 43_797, 4_878, 7_373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 133, 78, 65, 16, 10, 3_724, 1_538, 33_183, 11_303, 43_797, 1_938, 4, 870, 24_165, 29_105, 5, 739, 32_644, 33_183, 11_303, 36_173, 88, 80, 650, 7_821, 45_940, 6, 52, 2_559, 5, 1_836, 9, 5, 7_397, 13_171, 31, 5, 1_836, 9, 32_644, 33_183, 11_303, 4, 2]
],
'''token_type_ids''': [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
],
'''attention_mask''': [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
}
# fmt: on
snake_case : Tuple =[
'''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''',
'''ALBERT incorporates two parameter reduction techniques''',
'''The first one is a factorized embedding parameterization. By decomposing the large vocabulary'''
''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'''
''' vocabulary embedding.''',
]
self.assertDictEqual(encoding.data, _snake_case )
for expected, decoded in zip(_snake_case, _snake_case ):
self.assertEqual(_snake_case, _snake_case )
| 349 | 0 |
"""simple docstring"""
def __A ( a_ : int = 50 )-> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = [[0] * 3 for _ in range(length + 1 )]
for row_length in range(length + 1 ):
for tile_length in range(2 , 5 ):
for tile_start in range(row_length - tile_length + 1 ):
different_colour_ways_number[row_length][tile_length - 2] += (
different_colour_ways_number[row_length - tile_start - tile_length][
tile_length - 2
]
+ 1
)
return sum(different_colour_ways_number[length] )
if __name__ == "__main__":
print(f'''{solution() = }''')
| 721 |
"""simple docstring"""
from __future__ import annotations
from numpy import array, cos, cross, floataa, radians, sin
from numpy.typing import NDArray
def __A ( a_ : float , a_ : float , a_ : bool = False )-> list[float]:
'''simple docstring'''
if radian_mode:
return [magnitude * cos(a_ ), magnitude * sin(a_ )]
return [magnitude * cos(radians(a_ ) ), magnitude * sin(radians(a_ ) )]
def __A ( a_ : NDArray[floataa] , a_ : NDArray[floataa] , a_ : float = 10**-1 )-> bool:
'''simple docstring'''
SCREAMING_SNAKE_CASE : NDArray[floataa] = cross(a_ , a_ )
SCREAMING_SNAKE_CASE : float = sum(a_ )
return abs(a_ ) < eps
if __name__ == "__main__":
# Test to check if it works
lowerCamelCase__ : Optional[Any] = array(
[
polar_force(7_1_8.4, 180 - 30),
polar_force(8_7_9.5_4, 45),
polar_force(100, -90),
]
)
lowerCamelCase__ : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem 1 in image_data/2D_problems.jpg
lowerCamelCase__ : Union[str, Any] = array(
[
polar_force(30 * 9.8_1, 15),
polar_force(215, 180 - 45),
polar_force(264, 90 - 30),
]
)
lowerCamelCase__ : Any = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem in image_data/2D_problems_1.jpg
lowerCamelCase__ : Union[str, Any] = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]])
lowerCamelCase__ : Optional[int] = array([[0, 0], [6, 0], [10, 0], [12, 0]])
assert in_static_equilibrium(forces, location)
import doctest
doctest.testmod()
| 18 | 0 |
"""simple docstring"""
import numpy
class __a :
def __init__( self , a__ , a__ ):
_lowerCamelCase = input_array
# Random initial weights are assigned where first argument is the
# number of nodes in previous layer and second argument is the
# number of nodes in the next layer.
# Random initial weights are assigned.
# self.input_array.shape[1] is used to represent number of nodes in input layer.
# First hidden layer consists of 4 nodes.
_lowerCamelCase = numpy.random.rand(
self.input_array.shape[1] , 4 )
# Random initial values for the first hidden layer.
# First hidden layer has 4 nodes.
# Second hidden layer has 3 nodes.
_lowerCamelCase = numpy.random.rand(
4 , 3 )
# Random initial values for the second hidden layer.
# Second hidden layer has 3 nodes.
# Output layer has 1 node.
_lowerCamelCase = numpy.random.rand(3 , 1 )
# Real output values provided.
_lowerCamelCase = output_array
# Predicted output values by the neural network.
# Predicted_output array initially consists of zeroes.
_lowerCamelCase = numpy.zeros(output_array.shape )
def snake_case_ ( self ):
_lowerCamelCase = sigmoid(
numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) )
# layer_between_first_hidden_layer_and_second_hidden_layer is the layer
# connecting the first hidden set of nodes with the second hidden set of nodes.
_lowerCamelCase = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
# layer_between_second_hidden_layer_and_output is the layer connecting
# second hidden layer with the output node.
_lowerCamelCase = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return self.layer_between_second_hidden_layer_and_output
def snake_case_ ( self ):
_lowerCamelCase = numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , )
_lowerCamelCase = numpy.dot(
self.layer_between_input_and_first_hidden_layer.T , numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , )
_lowerCamelCase = numpy.dot(
self.input_array.T , numpy.dot(
numpy.dot(
2
* (self.output_array - self.predicted_output)
* sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , )
* sigmoid_derivative(
self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , )
* sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , )
self.input_layer_and_first_hidden_layer_weights += (
updated_input_layer_and_first_hidden_layer_weights
)
self.first_hidden_layer_and_second_hidden_layer_weights += (
updated_first_hidden_layer_and_second_hidden_layer_weights
)
self.second_hidden_layer_and_output_layer_weights += (
updated_second_hidden_layer_and_output_layer_weights
)
def snake_case_ ( self , a__ , a__ , a__ ):
for iteration in range(1 , iterations + 1 ):
_lowerCamelCase = self.feedforward()
self.back_propagation()
if give_loss:
_lowerCamelCase = numpy.mean(numpy.square(output - self.feedforward() ) )
print(F'Iteration {iteration} Loss: {loss}' )
def snake_case_ ( self , a__ ):
_lowerCamelCase = input_arr
_lowerCamelCase = sigmoid(
numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) )
_lowerCamelCase = sigmoid(
numpy.dot(
self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) )
_lowerCamelCase = sigmoid(
numpy.dot(
self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) )
return int(self.layer_between_second_hidden_layer_and_output > 0.6 )
def SCREAMING_SNAKE_CASE_ ( snake_case : int )-> Optional[int]:
return 1 / (1 + numpy.exp(-value ))
def SCREAMING_SNAKE_CASE_ ( snake_case : Optional[Any] )-> Dict:
return (value) * (1 - (value))
def SCREAMING_SNAKE_CASE_ ( )-> Optional[Any]:
_lowerCamelCase = numpy.array(
(
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
) , dtype=numpy.floataa , )
# True output values for the given input values.
_lowerCamelCase = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa )
# Calling neural network class.
_lowerCamelCase = TwoHiddenLayerNeuralNetwork(
input_array=_A , output_array=_A )
# Calling training function.
# Set give_loss to True if you want to see loss in every iteration.
neural_network.train(output=_A , iterations=10 , give_loss=_A )
return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) )
if __name__ == "__main__":
example()
| 650 |
'''simple docstring'''
import numpy as np
def lowerCamelCase__ ( _A ):
return 1 / (1 + np.exp(-vector ))
def lowerCamelCase__ ( _A ):
return vector * sigmoid(1.702 * vector )
if __name__ == "__main__":
import doctest
doctest.testmod() | 526 | 0 |
'''simple docstring'''
import hashlib
import unittest
from typing import Dict
import numpy as np
from transformers import (
MODEL_FOR_MASK_GENERATION_MAPPING,
TF_MODEL_FOR_MASK_GENERATION_MAPPING,
is_vision_available,
pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
if is_vision_available():
from PIL import Image
else:
class UpperCamelCase__ :
"""simple docstring"""
@staticmethod
def snake_case ( *__A : List[Any] , **__A : List[str] ):
"""simple docstring"""
pass
def A__ ( A_ ) -> str:
_lowercase = hashlib.mda(image.tobytes() )
return m.hexdigest()[:10]
def A__ ( A_ ) -> Dict:
_lowercase = np.array(lowerCAmelCase__ )
_lowercase = npimg.shape
return {"hash": hashimage(lowerCAmelCase__ ), "shape": shape}
@is_pipeline_test
@require_vision
@require_torch
class UpperCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ = dict(
(list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) )
UpperCAmelCase__ = dict(
(list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) )
def snake_case ( self : Union[str, Any] , __A : Optional[int] , __A : Union[str, Any] , __A : int ):
"""simple docstring"""
_lowercase = MaskGenerationPipeline(model=_a , image_processor=_a )
return image_segmenter, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def snake_case ( self : Tuple , __A : Any , __A : str ):
"""simple docstring"""
pass
@require_tf
@unittest.skip("Image segmentation not implemented in TF" )
def snake_case ( self : Dict ):
"""simple docstring"""
pass
@slow
@require_torch
def snake_case ( self : Any ):
"""simple docstring"""
_lowercase = pipeline("mask-generation" , model="facebook/sam-vit-huge" )
_lowercase = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg" , points_per_batch=2_5_6 )
# Shortening by hashing
_lowercase = []
for i, o in enumerate(outputs["masks"] ):
new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}]
# fmt: off
self.assertEqual(
nested_simplify(_a , decimals=4 ) , [
{"mask": {"hash": "115ad19f5f", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_4_4_4},
{"mask": {"hash": "6affa964c6", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_2_1},
{"mask": {"hash": "dfe28a0388", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_1_6_7},
{"mask": {"hash": "c0a5f4a318", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_1_3_2},
{"mask": {"hash": "fe8065c197", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_0_5_3},
{"mask": {"hash": "e2d0b7a0b7", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_9_6_7},
{"mask": {"hash": "453c7844bd", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_9_3},
{"mask": {"hash": "3d44f2926d", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_9_0_9},
{"mask": {"hash": "64033ddc3f", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_8_7_9},
{"mask": {"hash": "801064ff79", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_8_3_4},
{"mask": {"hash": "6172f276ef", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_7_1_6},
{"mask": {"hash": "b49e60e084", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_6_1_2},
{"mask": {"hash": "a811e775fd", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_5_9_9},
{"mask": {"hash": "a6a8ebcf4b", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_5_5_2},
{"mask": {"hash": "9d8257e080", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_5_3_2},
{"mask": {"hash": "32de6454a8", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_5_1_6},
{"mask": {"hash": "af3d4af2c8", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_4_9_9},
{"mask": {"hash": "3c6db475fb", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_4_8_3},
{"mask": {"hash": "c290813fb9", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_4_6_4},
{"mask": {"hash": "b6f0b8f606", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_4_3},
{"mask": {"hash": "92ce16bfdf", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_4_3},
{"mask": {"hash": "c749b25868", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_4_0_8},
{"mask": {"hash": "efb6cab859", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_3_3_5},
{"mask": {"hash": "1ff2eafb30", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_3_2_6},
{"mask": {"hash": "788b798e24", "shape": (4_8_0, 6_4_0)}, "scores": 0.9_2_6_2},
{"mask": {"hash": "abea804f0e", "shape": (4_8_0, 6_4_0)}, "scores": 0.8_9_9_9},
{"mask": {"hash": "7b9e8ddb73", "shape": (4_8_0, 6_4_0)}, "scores": 0.8_9_8_6},
{"mask": {"hash": "cd24047c8a", "shape": (4_8_0, 6_4_0)}, "scores": 0.8_9_8_4},
{"mask": {"hash": "6943e6bcbd", "shape": (4_8_0, 6_4_0)}, "scores": 0.8_8_7_3},
{"mask": {"hash": "b5f47c9191", "shape": (4_8_0, 6_4_0)}, "scores": 0.8_8_7_1}
] , )
# fmt: on
@require_torch
@slow
def snake_case ( self : List[str] ):
"""simple docstring"""
_lowercase = "facebook/sam-vit-huge"
_lowercase = pipeline("mask-generation" , model=_a )
_lowercase = image_segmenter(
"http://images.cocodataset.org/val2017/000000039769.jpg" , pred_iou_thresh=1 , points_per_batch=2_5_6 )
# Shortening by hashing
_lowercase = []
for i, o in enumerate(outputs["masks"] ):
new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}]
self.assertEqual(
nested_simplify(_a , decimals=4 ) , [
{"mask": {"hash": "115ad19f5f", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_4_4_4},
{"mask": {"hash": "6affa964c6", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_2_1_0},
{"mask": {"hash": "dfe28a0388", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_1_6_7},
{"mask": {"hash": "c0a5f4a318", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_1_3_2},
{"mask": {"hash": "fe8065c197", "shape": (4_8_0, 6_4_0)}, "scores": 1.0_0_5_3},
] , )
| 721 |
'''simple docstring'''
import numpy as np
from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey
def A__ ( A_ , A_ , A_ , A_ , A_ , A_ ) -> np.ndarray:
# prepare kernel
# the kernel size have to be odd
if (ksize % 2) == 0:
_lowercase = ksize + 1
_lowercase = np.zeros((ksize, ksize) , dtype=np.floataa )
# each value
for y in range(A_ ):
for x in range(A_ ):
# distance from center
_lowercase = x - ksize // 2
_lowercase = y - ksize // 2
# degree to radiant
_lowercase = theta / 180 * np.pi
_lowercase = np.cos(_theta )
_lowercase = np.sin(_theta )
# get kernel x
_lowercase = cos_theta * px + sin_theta * py
# get kernel y
_lowercase = -sin_theta * px + cos_theta * py
# fill kernel
_lowercase = np.exp(
-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi )
return gabor
if __name__ == "__main__":
import doctest
doctest.testmod()
# read original image
__magic_name__ : List[Any] = imread('''../image_data/lena.jpg''')
# turn image in gray scale value
__magic_name__ : str = cvtColor(img, COLOR_BGR2GRAY)
# Apply multiple Kernel to detect edges
__magic_name__ : List[Any] = np.zeros(gray.shape[:2])
for theta in [0, 30, 60, 90, 120, 150]:
__magic_name__ : int = gabor_filter_kernel(10, 8, theta, 10, 0, 0)
out += filteraD(gray, CV_8UC3, kernel_aa)
__magic_name__ : int = out / out.max() * 255
__magic_name__ : str = out.astype(np.uinta)
imshow('''Original''', gray)
imshow('''Gabor filter with 20x20 mask and 6 directions''', out)
waitKey(0)
| 602 | 0 |
'''simple docstring'''
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Features, Value
from .base import TaskTemplate
@dataclass(frozen=UpperCAmelCase_ )
class lowerCAmelCase__ ( UpperCAmelCase_ ):
'''simple docstring'''
# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
_lowerCamelCase =field(default="summarization" , metadata={"include_in_asdict_even_if_is_default": True} )
_lowerCamelCase =Features({"text": Value("string" )} )
_lowerCamelCase =Features({"summary": Value("string" )} )
_lowerCamelCase ="text"
_lowerCamelCase ="summary"
@property
def __snake_case ( self : List[Any] ):
return {self.text_column: "text", self.summary_column: "summary"}
| 51 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__a : Optional[Any] = logging.get_logger(__name__)
__a : Dict = {
"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 __lowercase ( lowercase_ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE = "realm"
def __init__( self : str , UpperCamelCase_ : List[Any]=30_522 , UpperCamelCase_ : Dict=768 , UpperCamelCase_ : Union[str, Any]=128 , UpperCamelCase_ : Tuple=12 , UpperCamelCase_ : Optional[Any]=12 , UpperCamelCase_ : Optional[int]=8 , UpperCamelCase_ : str=3_072 , UpperCamelCase_ : List[str]="gelu_new" , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : str=512 , UpperCamelCase_ : int=2 , UpperCamelCase_ : str=0.02 , UpperCamelCase_ : List[Any]=1e-12 , UpperCamelCase_ : str=256 , UpperCamelCase_ : List[str]=10 , UpperCamelCase_ : int=1e-3 , UpperCamelCase_ : List[str]=5 , UpperCamelCase_ : Tuple=320 , UpperCamelCase_ : List[str]=13_353_718 , UpperCamelCase_ : Tuple=5_000 , UpperCamelCase_ : Optional[int]=1 , UpperCamelCase_ : List[str]=0 , UpperCamelCase_ : Union[str, Any]=2 , **UpperCamelCase_ : List[Any] , ):
"""simple docstring"""
super().__init__(pad_token_id=UpperCamelCase_ , bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ )
# Common config
__A = vocab_size
__A = max_position_embeddings
__A = hidden_size
__A = retriever_proj_size
__A = num_hidden_layers
__A = num_attention_heads
__A = num_candidates
__A = intermediate_size
__A = hidden_act
__A = hidden_dropout_prob
__A = attention_probs_dropout_prob
__A = initializer_range
__A = type_vocab_size
__A = layer_norm_eps
# Reader config
__A = span_hidden_size
__A = max_span_width
__A = reader_layer_norm_eps
__A = reader_beam_size
__A = reader_seq_len
# Retrieval config
__A = num_block_records
__A = searcher_beam_size
| 637 | 0 |
'''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 A ( A_ : Dict , A_ : Optional[Any] , A_ : Dict , A_ : Union[str, Any] , A_ : List[str] ):
# 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
snake_case : Dict = TapasConfig.from_json_file(A_ )
# set absolute/relative position embeddings parameter
snake_case : str = reset_position_index_per_cell
# set remaining parameters of TapasConfig as well as the model based on the task
if task == "SQA":
snake_case : Union[str, Any] = TapasForQuestionAnswering(config=A_ )
elif task == "WTQ":
# run_task_main.py hparams
snake_case : int = 4
snake_case : Optional[int] = True
# hparam_utils.py hparams
snake_case : List[str] = 0.66_4694
snake_case : List[str] = 0.20_7951
snake_case : int = 0.12_1194
snake_case : Tuple = True
snake_case : Tuple = True
snake_case : int = False
snake_case : Optional[int] = 0.035_2513
snake_case : Optional[Any] = TapasForQuestionAnswering(config=A_ )
elif task == "WIKISQL_SUPERVISED":
# run_task_main.py hparams
snake_case : Dict = 4
snake_case : Union[str, Any] = False
# hparam_utils.py hparams
snake_case : Any = 36.4519
snake_case : str = 0.90_3421
snake_case : Union[str, Any] = 222.088
snake_case : int = True
snake_case : Union[str, Any] = True
snake_case : Optional[Any] = True
snake_case : int = 0.76_3141
snake_case : Optional[int] = TapasForQuestionAnswering(config=A_ )
elif task == "TABFACT":
snake_case : Union[str, Any] = TapasForSequenceClassification(config=A_ )
elif task == "MLM":
snake_case : List[str] = TapasForMaskedLM(config=A_ )
elif task == "INTERMEDIATE_PRETRAINING":
snake_case : Tuple = 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}""" )
snake_case : List[str] = 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__":
UpperCAmelCase = 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."
)
UpperCAmelCase = 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,
)
| 555 |
'''simple docstring'''
import json
from typing import TYPE_CHECKING, List, Optional, Tuple
from tokenizers import pre_tokenizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_gpta import GPTaTokenizer
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
UpperCAmelCase = logging.get_logger(__name__)
UpperCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
UpperCAmelCase = {
"vocab_file": {
"gpt2": "https://huggingface.co/gpt2/resolve/main/vocab.json",
"gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/vocab.json",
"gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/vocab.json",
"gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/vocab.json",
"distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/vocab.json",
},
"merges_file": {
"gpt2": "https://huggingface.co/gpt2/resolve/main/merges.txt",
"gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/merges.txt",
"gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/merges.txt",
"gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/merges.txt",
"distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/merges.txt",
},
"tokenizer_file": {
"gpt2": "https://huggingface.co/gpt2/resolve/main/tokenizer.json",
"gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json",
"gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/tokenizer.json",
"gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json",
"distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/tokenizer.json",
},
}
UpperCAmelCase = {
"gpt2": 1_024,
"gpt2-medium": 1_024,
"gpt2-large": 1_024,
"gpt2-xl": 1_024,
"distilgpt2": 1_024,
}
class a ( __magic_name__ ):
_snake_case = VOCAB_FILES_NAMES
_snake_case = PRETRAINED_VOCAB_FILES_MAP
_snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_snake_case = ['''input_ids''', '''attention_mask''']
_snake_case = GPTaTokenizer
def __init__( self : Union[str, Any], SCREAMING_SNAKE_CASE_ : Union[str, Any]=None, SCREAMING_SNAKE_CASE_ : Any=None, SCREAMING_SNAKE_CASE_ : List[str]=None, SCREAMING_SNAKE_CASE_ : Union[str, Any]="<|endoftext|>", SCREAMING_SNAKE_CASE_ : Optional[int]="<|endoftext|>", SCREAMING_SNAKE_CASE_ : Dict="<|endoftext|>", SCREAMING_SNAKE_CASE_ : Union[str, Any]=False, **SCREAMING_SNAKE_CASE_ : Tuple, ):
super().__init__(
SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, tokenizer_file=SCREAMING_SNAKE_CASE_, unk_token=SCREAMING_SNAKE_CASE_, bos_token=SCREAMING_SNAKE_CASE_, eos_token=SCREAMING_SNAKE_CASE_, add_prefix_space=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, )
snake_case : Optional[Any] = kwargs.pop('''add_bos_token''', SCREAMING_SNAKE_CASE_ )
snake_case : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get('''add_prefix_space''', SCREAMING_SNAKE_CASE_ ) != add_prefix_space:
snake_case : List[Any] = getattr(SCREAMING_SNAKE_CASE_, pre_tok_state.pop('''type''' ) )
snake_case : Dict = add_prefix_space
snake_case : List[Any] = pre_tok_class(**SCREAMING_SNAKE_CASE_ )
snake_case : Optional[Any] = add_prefix_space
def __snake_case ( self : Optional[Any], *SCREAMING_SNAKE_CASE_ : Dict, **SCREAMING_SNAKE_CASE_ : List[str] ):
snake_case : str = kwargs.get('''is_split_into_words''', SCREAMING_SNAKE_CASE_ )
assert self.add_prefix_space or not is_split_into_words, (
F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Union[str, Any], *SCREAMING_SNAKE_CASE_ : Tuple, **SCREAMING_SNAKE_CASE_ : int ):
snake_case : int = kwargs.get('''is_split_into_words''', SCREAMING_SNAKE_CASE_ )
assert self.add_prefix_space or not is_split_into_words, (
F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
"to use it with pretokenized inputs."
)
return super()._encode_plus(*SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : List[Any], SCREAMING_SNAKE_CASE_ : str, SCREAMING_SNAKE_CASE_ : Optional[str] = None ):
snake_case : List[Any] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_, name=SCREAMING_SNAKE_CASE_ )
return tuple(SCREAMING_SNAKE_CASE_ )
def __snake_case ( self : Optional[Any], SCREAMING_SNAKE_CASE_ : "Conversation" ):
snake_case : int = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(SCREAMING_SNAKE_CASE_, add_special_tokens=SCREAMING_SNAKE_CASE_ ) + [self.eos_token_id] )
if len(SCREAMING_SNAKE_CASE_ ) > self.model_max_length:
snake_case : str = input_ids[-self.model_max_length :]
return input_ids
| 555 | 1 |
import sys
import webbrowser
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
if __name__ == "__main__":
print('''Googling.....''')
snake_case__ : Optional[int] = '''https://www.google.com/search?q=''' + ''' '''.join(sys.argv[1:])
snake_case__ : List[Any] = requests.get(url, headers={'''UserAgent''': UserAgent().random})
# res.raise_for_status()
with open('''project1a.html''', '''wb''') as out_file: # only for knowing the class
for data in res.iter_content(1_0_0_0_0):
out_file.write(data)
snake_case__ : str = BeautifulSoup(res.text, '''html.parser''')
snake_case__ : Any = list(soup.select('''.eZt8xd'''))[:5]
print(len(links))
for link in links:
if link.text == "Maps":
webbrowser.open(link.get('''href'''))
else:
webbrowser.open(F"""https://google.com{link.get("href")}""")
| 392 |
"""simple docstring"""
from __future__ import annotations
def lowercase ( __snake_case : list[list[int]] ):
lowercase_ : Optional[Any] = len(__snake_case )
# We need to create solution object to save path.
lowercase_ : List[str] = [[0 for _ in range(__snake_case )] for _ in range(__snake_case )]
lowercase_ : List[Any] = run_maze(__snake_case , 0 , 0 , __snake_case )
if solved:
print('''\n'''.join(str(__snake_case ) for row in solutions ) )
else:
print('''No solution exists!''' )
return solved
def lowercase ( __snake_case : list[list[int]] , __snake_case : int , __snake_case : int , __snake_case : list[list[int]] ):
lowercase_ : int = len(__snake_case )
# Final check point.
if i == j == (size - 1):
lowercase_ : List[Any] = 1
return True
lowercase_ : Optional[int] = (not i < 0) and (not j < 0) # Check lower bounds
lowercase_ : str = (i < size) and (j < size) # Check upper bounds
if lower_flag and upper_flag:
# check for already visited and block points.
lowercase_ : Optional[int] = (not solutions[i][j]) and (not maze[i][j])
if block_flag:
# check visited
lowercase_ : List[Any] = 1
# check for directions
if (
run_maze(__snake_case , i + 1 , __snake_case , __snake_case )
or run_maze(__snake_case , __snake_case , j + 1 , __snake_case )
or run_maze(__snake_case , i - 1 , __snake_case , __snake_case )
or run_maze(__snake_case , __snake_case , j - 1 , __snake_case )
):
return True
lowercase_ : List[Any] = 0
return False
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 231 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
lowercase__ : str = {
"""configuration_layoutlmv3""": [
"""LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""LayoutLMv3Config""",
"""LayoutLMv3OnnxConfig""",
],
"""processing_layoutlmv3""": ["""LayoutLMv3Processor"""],
"""tokenization_layoutlmv3""": ["""LayoutLMv3Tokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ : Any = ["""LayoutLMv3TokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ : Any = [
"""LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""LayoutLMv3ForQuestionAnswering""",
"""LayoutLMv3ForSequenceClassification""",
"""LayoutLMv3ForTokenClassification""",
"""LayoutLMv3Model""",
"""LayoutLMv3PreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ : Union[str, Any] = [
"""TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFLayoutLMv3ForQuestionAnswering""",
"""TFLayoutLMv3ForSequenceClassification""",
"""TFLayoutLMv3ForTokenClassification""",
"""TFLayoutLMv3Model""",
"""TFLayoutLMv3PreTrainedModel""",
]
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ : str = ["""LayoutLMv3FeatureExtractor"""]
lowercase__ : Tuple = ["""LayoutLMv3ImageProcessor"""]
if TYPE_CHECKING:
from .configuration_layoutlmva import (
LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
LayoutLMvaConfig,
LayoutLMvaOnnxConfig,
)
from .processing_layoutlmva import LayoutLMvaProcessor
from .tokenization_layoutlmva import LayoutLMvaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_layoutlmva import (
LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaModel,
LayoutLMvaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_layoutlmva import (
TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
TFLayoutLMvaModel,
TFLayoutLMvaPreTrainedModel,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
from .image_processing_layoutlmva import LayoutLMvaImageProcessor
else:
import sys
lowercase__ : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 708 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available, is_torch_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow
if is_tf_available():
from transformers import (
AutoConfig,
BertConfig,
GPTaConfig,
TaConfig,
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
)
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
if is_torch_available():
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForPreTraining,
AutoModelForQuestionAnswering,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoModelWithLMHead,
BertForMaskedLM,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertModel,
GPTaLMHeadModel,
RobertaForMaskedLM,
TaForConditionalGeneration,
)
@is_pt_tf_cross_test
class UpperCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
@slow
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
lowerCAmelCase_ : List[str] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Tuple = TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : str = AutoModel.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Dict ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
lowerCAmelCase_ : Optional[Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Dict = TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Any = AutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Any ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase_ : int = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : str = TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ ,lowerCAmelCase_ : List[str] = TFAutoModelForCausalLM.from_pretrained(
SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Tuple = AutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ ,lowerCAmelCase_ : Dict = AutoModelForCausalLM.from_pretrained(
SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : List[Any] ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase_ : Optional[int] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Tuple = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Tuple = AutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Any ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase_ : Optional[Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Union[str, Any] = TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ ,lowerCAmelCase_ : List[Any] = TFAutoModelForMaskedLM.from_pretrained(
SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Union[str, Any] = AutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ ,lowerCAmelCase_ : Tuple = AutoModelForMaskedLM.from_pretrained(
SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Any ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase_ : Optional[int] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ ,lowerCAmelCase_ : List[str] = TFAutoModelForSeqaSeqLM.from_pretrained(
SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Any = AutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ ,lowerCAmelCase_ : Any = AutoModelForSeqaSeqLM.from_pretrained(
SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Dict ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
lowerCAmelCase_ : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Optional[int] = TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Tuple ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
lowerCAmelCase_ : List[Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : str = TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowerCAmelCase_ : List[str] = AutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def SCREAMING_SNAKE_CASE__ ( self : int ):
lowerCAmelCase_ : str = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE_ ) , 1_4_4_1_0 )
lowerCAmelCase_ : str = AutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE_ ) , 1_4_4_1_0 )
def SCREAMING_SNAKE_CASE__ ( self : List[str] ):
lowerCAmelCase_ : List[Any] = TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ , from_pt=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE_ ) , 1_4_4_1_0 )
lowerCAmelCase_ : Tuple = AutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE_ , from_tf=SCREAMING_SNAKE_CASE_ )
self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
self.assertEqual(model.num_parameters() , 1_4_4_1_0 )
self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE_ ) , 1_4_4_1_0 )
| 317 | 0 |
def __UpperCamelCase ( _A ):
return " ".join(
''''''.join(word[::-1] ) if len(_A ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('''Hey wollef sroirraw'''))
| 431 |
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel
@require_tf
class A :
__snake_case = MBartConfig
__snake_case = {}
__snake_case = 'gelu'
def __init__( self, UpperCamelCase__, UpperCamelCase__=13, UpperCamelCase__=7, UpperCamelCase__=True, UpperCamelCase__=False, UpperCamelCase__=99, UpperCamelCase__=32, UpperCamelCase__=2, UpperCamelCase__=4, UpperCamelCase__=37, UpperCamelCase__=0.1, UpperCamelCase__=0.1, UpperCamelCase__=20, UpperCamelCase__=2, UpperCamelCase__=1, UpperCamelCase__=0, ):
"""simple docstring"""
lowerCAmelCase_ = parent
lowerCAmelCase_ = batch_size
lowerCAmelCase_ = seq_length
lowerCAmelCase_ = is_training
lowerCAmelCase_ = use_labels
lowerCAmelCase_ = vocab_size
lowerCAmelCase_ = hidden_size
lowerCAmelCase_ = num_hidden_layers
lowerCAmelCase_ = num_attention_heads
lowerCAmelCase_ = intermediate_size
lowerCAmelCase_ = hidden_dropout_prob
lowerCAmelCase_ = attention_probs_dropout_prob
lowerCAmelCase_ = max_position_embeddings
lowerCAmelCase_ = eos_token_id
lowerCAmelCase_ = pad_token_id
lowerCAmelCase_ = bos_token_id
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size )
lowerCAmelCase_ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 )
lowerCAmelCase_ = tf.concat([input_ids, eos_tensor], axis=1 )
lowerCAmelCase_ = ids_tensor([self.batch_size, self.seq_length], self.vocab_size )
lowerCAmelCase_ = self.config_cls(
vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, )
lowerCAmelCase_ = prepare_mbart_inputs_dict(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
return config, inputs_dict
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = TFMBartModel(config=UpperCamelCase__ ).get_decoder()
lowerCAmelCase_ = inputs_dict['''input_ids''']
lowerCAmelCase_ = input_ids[:1, :]
lowerCAmelCase_ = inputs_dict['''attention_mask'''][:1, :]
lowerCAmelCase_ = inputs_dict['''head_mask''']
lowerCAmelCase_ = 1
# first forward pass
lowerCAmelCase_ = model(UpperCamelCase__, attention_mask=UpperCamelCase__, head_mask=UpperCamelCase__, use_cache=UpperCamelCase__ )
lowerCAmelCase_ , lowerCAmelCase_ = outputs.to_tuple()
lowerCAmelCase_ = past_key_values[1]
def __UpperCamelCase ( _A , _A , _A , _A=None , _A=None , _A=None , _A=None , _A=None , ):
if attention_mask is None:
lowerCAmelCase_ = tf.cast(tf.math.not_equal(_A , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
lowerCAmelCase_ = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
lowerCAmelCase_ = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
lowerCAmelCase_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
lowerCAmelCase_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class A ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
__snake_case = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
__snake_case = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
__snake_case = (
{
'conversational': TFMBartForConditionalGeneration,
'feature-extraction': TFMBartModel,
'summarization': TFMBartForConditionalGeneration,
'text2text-generation': TFMBartForConditionalGeneration,
'translation': TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
__snake_case = True
__snake_case = False
__snake_case = False
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = TFMBartModelTester(self )
lowerCAmelCase_ = ConfigTester(self, config_class=UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase__ )
@require_sentencepiece
@require_tokenizers
@require_tf
class A ( unittest.TestCase ):
__snake_case = [
' UN Chief Says There Is No Military Solution in Syria',
]
__snake_case = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
]
__snake_case = 'facebook/mbart-large-en-ro'
@cached_property
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
return AutoTokenizer.from_pretrained(self.model_name )
@cached_property
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
return model
def SCREAMING_SNAKE_CASE__ ( self, **UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = self.translate_src_text(**UpperCamelCase__ )
self.assertListEqual(self.expected_text, UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self, **UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = self.tokenizer(self.src_text, **UpperCamelCase__, return_tensors='''tf''' )
lowerCAmelCase_ = self.model.generate(
model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2 )
lowerCAmelCase_ = self.tokenizer.batch_decode(UpperCamelCase__, skip_special_tokens=UpperCamelCase__ )
return generated_words
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
self._assert_generated_batch_equal_expected()
| 431 | 1 |
"""simple docstring"""
import json
import os
from typing import Dict, List, Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_lowercase : str = logging.get_logger(__name__)
_lowercase : Dict = {
'vocab_file': 'vocab.json',
'tokenizer_config_file': 'tokenizer_config.json',
'merges_file': 'merges.txt',
}
_lowercase : int = {
'vocab_file': {
'facebook/s2t-wav2vec2-large-en-de': (
'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json'
),
},
'tokenizer_config_file': {
'facebook/s2t-wav2vec2-large-en-de': (
'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json'
),
},
'merges_file': {
'facebook/s2t-wav2vec2-large-en-de': (
'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt'
),
},
}
_lowercase : Union[str, Any] = '</w>'
_lowercase : Optional[int] = '@@ '
def lowercase__ ( snake_case_ :Any ):
__UpperCAmelCase = set()
__UpperCAmelCase = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
__UpperCAmelCase = char
return pairs
# Speech2Text2 has no max input length
_lowercase : List[Any] = {'facebook/s2t-wav2vec2-large-en-de': 10_24}
class _UpperCAmelCase ( _lowerCAmelCase ):
a__ : Optional[int] = VOCAB_FILES_NAMES
a__ : Any = PRETRAINED_VOCAB_FILES_MAP
a__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a__ : str = ["input_ids", "attention_mask"]
def __init__( self : List[Any] , _lowercase : Any , _lowercase : List[Any]="<s>" , _lowercase : List[str]="<pad>" , _lowercase : List[Any]="</s>" , _lowercase : Union[str, Any]="<unk>" , _lowercase : List[str]=False , _lowercase : Optional[int]=None , **_lowercase : Dict , ):
super().__init__(
unk_token=_lowercase , bos_token=_lowercase , eos_token=_lowercase , pad_token=_lowercase , do_lower_case=_lowercase , **_lowercase , )
__UpperCAmelCase = do_lower_case
with open(_lowercase , encoding='''utf-8''' ) as vocab_handle:
__UpperCAmelCase = json.load(_lowercase )
__UpperCAmelCase = {v: k for k, v in self.encoder.items()}
if merges_file is None:
logger.info(F'''No merges files provided. {self.__class__.__name__} can only be used for decoding.''' )
__UpperCAmelCase = None
__UpperCAmelCase = None
else:
with open(_lowercase , encoding='''utf-8''' ) as merges_handle:
__UpperCAmelCase = merges_handle.read().split('''\n''' )[:-1]
__UpperCAmelCase = [tuple(merge.split()[:2] ) for merge in merges]
__UpperCAmelCase = dict(zip(_lowercase , range(len(_lowercase ) ) ) )
__UpperCAmelCase = {}
@property
def a ( self : List[str] ):
return len(self.decoder )
def a ( self : Optional[Any] ):
return dict(self.encoder , **self.added_tokens_encoder )
def a ( self : List[Any] , _lowercase : Any ):
__UpperCAmelCase = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,)
if token in self.cache:
return self.cache[token]
__UpperCAmelCase = get_pairs(_lowercase )
if not pairs:
return token
while True:
__UpperCAmelCase = min(_lowercase , key=lambda _lowercase : self.bpe_ranks.get(_lowercase , float('''inf''' ) ) )
if bigram not in self.bpe_ranks:
break
__UpperCAmelCase , __UpperCAmelCase = bigram
__UpperCAmelCase = []
__UpperCAmelCase = 0
while i < len(_lowercase ):
try:
__UpperCAmelCase = word.index(_lowercase , _lowercase )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
__UpperCAmelCase = j
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
__UpperCAmelCase = tuple(_lowercase )
__UpperCAmelCase = new_word
if len(_lowercase ) == 1:
break
else:
__UpperCAmelCase = get_pairs(_lowercase )
__UpperCAmelCase = ''' '''.join(_lowercase )
if word == "\n " + BPE_TOKEN_MERGES:
__UpperCAmelCase = '''\n''' + BPE_TOKEN_MERGES
if word.endswith(_lowercase ):
__UpperCAmelCase = word.replace(_lowercase , '''''' )
__UpperCAmelCase = word.replace(''' ''' , _lowercase )
__UpperCAmelCase = word
return word
def a ( self : Any , _lowercase : Optional[Any] ):
if self.bpe_ranks is None:
raise ValueError(
'''This tokenizer was instantiated without a `merges.txt` file, so'''
''' that it can only be used for decoding, not for encoding.'''
'''Make sure to provide `merges.txt` file at instantiation to enable '''
'''encoding.''' )
if self.do_lower_case:
__UpperCAmelCase = text.lower()
__UpperCAmelCase = text.split()
__UpperCAmelCase = []
for token in text:
if token:
split_tokens.extend(list(self.bpe(_lowercase ).split(''' ''' ) ) )
return split_tokens
def a ( self : Optional[int] , _lowercase : str ):
return self.encoder.get(_lowercase , self.encoder.get(self.unk_token ) )
def a ( self : List[str] , _lowercase : int ):
__UpperCAmelCase = self.decoder.get(_lowercase , self.unk_token )
return result
def a ( self : Tuple , _lowercase : List[str] ):
__UpperCAmelCase = ''' '''.join(_lowercase )
# make sure @@ tokens are concatenated
__UpperCAmelCase = ''''''.join(string.split(_lowercase ) )
return string
def a ( self : Optional[Any] , _lowercase : str , _lowercase : Optional[str] = None ):
if not os.path.isdir(_lowercase ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
__UpperCAmelCase = os.path.join(
_lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
__UpperCAmelCase = 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''' )
__UpperCAmelCase = 0
if self.bpe_ranks is None:
return (vocab_file,)
with open(_lowercase , '''w''' , encoding='''utf-8''' ) as writer:
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _lowercase : kv[1] ):
if index != token_index:
logger.warning(
F'''Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.'''
''' Please check that the tokenizer is not corrupted!''' )
__UpperCAmelCase = token_index
writer.write(''' '''.join(_lowercase ) + '''\n''' )
index += 1
return (vocab_file, merges_file)
| 397 |
"""simple docstring"""
import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch
import numpy as np
import pytest
from absl.testing import parameterized
import datasets
from datasets import load_metric
from .utils import for_all_test_methods, local, slow
# mark all tests as integration
_lowercase : str = pytest.mark.integration
_lowercase : int = {'comet'}
_lowercase : str = importlib.util.find_spec('fairseq') is not None
_lowercase : Union[str, Any] = {'code_eval'}
_lowercase : Optional[Any] = os.name == 'nt'
_lowercase : Union[str, Any] = {'bertscore', 'frugalscore', 'perplexity'}
_lowercase : Optional[Any] = importlib.util.find_spec('transformers') is not None
def lowercase__ ( snake_case_ :int ):
@wraps(snake_case_ )
def wrapper(self :List[Any] , snake_case_ :Dict ):
if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
self.skipTest('''"test requires Fairseq"''' )
else:
test_case(self , snake_case_ )
return wrapper
def lowercase__ ( snake_case_ :str ):
@wraps(snake_case_ )
def wrapper(self :List[str] , snake_case_ :int ):
if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
self.skipTest('''"test requires transformers"''' )
else:
test_case(self , snake_case_ )
return wrapper
def lowercase__ ( snake_case_ :Union[str, Any] ):
@wraps(snake_case_ )
def wrapper(self :List[Any] , snake_case_ :Union[str, Any] ):
if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
self.skipTest('''"test not supported on Windows"''' )
else:
test_case(self , snake_case_ )
return wrapper
def lowercase__ ( ):
__UpperCAmelCase = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )]
return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished
@parameterized.named_parameters(get_local_metric_names() )
@for_all_test_methods(
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
@local
class _UpperCAmelCase ( parameterized.TestCase ):
a__ : Union[str, Any] = {}
a__ : Optional[int] = None
@pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' )
@pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' )
def a ( self : List[Any] , _lowercase : Any ):
__UpperCAmelCase = '''[...]'''
__UpperCAmelCase = importlib.import_module(
datasets.load.metric_module_factory(os.path.join('''metrics''' , _lowercase ) ).module_path )
__UpperCAmelCase = datasets.load.import_main_class(metric_module.__name__ , dataset=_lowercase )
# check parameters
__UpperCAmelCase = inspect.signature(metric._compute ).parameters
self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs
# run doctest
with self.patch_intensive_calls(_lowercase , metric_module.__name__ ):
with self.use_local_metrics():
try:
__UpperCAmelCase = doctest.testmod(_lowercase , verbose=_lowercase , raise_on_error=_lowercase )
except doctest.UnexpectedException as e:
raise e.exc_info[1] # raise the exception that doctest caught
self.assertEqual(results.failed , 0 )
self.assertGreater(results.attempted , 1 )
@slow
def a ( self : List[str] , _lowercase : Union[str, Any] ):
__UpperCAmelCase = '''[...]'''
__UpperCAmelCase = importlib.import_module(
datasets.load.metric_module_factory(os.path.join('''metrics''' , _lowercase ) ).module_path )
# run doctest
with self.use_local_metrics():
__UpperCAmelCase = doctest.testmod(_lowercase , verbose=_lowercase , raise_on_error=_lowercase )
self.assertEqual(results.failed , 0 )
self.assertGreater(results.attempted , 1 )
@contextmanager
def a ( self : Any , _lowercase : Optional[int] , _lowercase : Any ):
if metric_name in self.INTENSIVE_CALLS_PATCHER:
with self.INTENSIVE_CALLS_PATCHER[metric_name](_lowercase ):
yield
else:
yield
@contextmanager
def a ( self : Optional[int] ):
def load_local_metric(_lowercase : str , *_lowercase : Dict , **_lowercase : Tuple ):
return load_metric(os.path.join('''metrics''' , _lowercase ) , *_lowercase , **_lowercase )
with patch('''datasets.load_metric''' ) as mock_load_metric:
__UpperCAmelCase = load_local_metric
yield
@classmethod
def a ( cls : Tuple , _lowercase : Optional[int] ):
def wrapper(_lowercase : List[str] ):
__UpperCAmelCase = contextmanager(_lowercase )
__UpperCAmelCase = patcher
return patcher
return wrapper
@LocalMetricTest.register_intensive_calls_patcher('''bleurt''' )
def lowercase__ ( snake_case_ :str ):
import tensorflow.compat.va as tf
from bleurt.score import Predictor
tf.flags.DEFINE_string('''sv''' , '''''' , '''''' ) # handle pytest cli flags
class _UpperCAmelCase ( _lowerCAmelCase ):
def a ( self : List[Any] , _lowercase : Union[str, Any] ):
assert len(input_dict['''input_ids'''] ) == 2
return np.array([1.03, 1.04] )
# mock predict_fn which is supposed to do a forward pass with a bleurt model
with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor:
__UpperCAmelCase = MockedPredictor()
yield
@LocalMetricTest.register_intensive_calls_patcher('''bertscore''' )
def lowercase__ ( snake_case_ :Optional[int] ):
import torch
def bert_cos_score_idf(snake_case_ :List[str] , snake_case_ :Optional[Any] , *snake_case_ :Tuple , **snake_case_ :str ):
return torch.tensor([[1.0, 1.0, 1.0]] * len(snake_case_ ) )
# mock get_model which is supposed to do download a bert model
# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
with patch('''bert_score.scorer.get_model''' ), patch(
'''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf:
__UpperCAmelCase = bert_cos_score_idf
yield
@LocalMetricTest.register_intensive_calls_patcher('''comet''' )
def lowercase__ ( snake_case_ :Dict ):
def load_from_checkpoint(snake_case_ :List[Any] ):
class _UpperCAmelCase :
def a ( self : Optional[Any] , _lowercase : Tuple , *_lowercase : Dict , **_lowercase : Dict ):
assert len(_lowercase ) == 2
__UpperCAmelCase = [0.19, 0.92]
return scores, sum(_lowercase ) / len(_lowercase )
return Model()
# mock load_from_checkpoint which is supposed to do download a bert model
# mock load_from_checkpoint which is supposed to do download a bert model
with patch('''comet.download_model''' ) as mock_download_model:
__UpperCAmelCase = None
with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint:
__UpperCAmelCase = load_from_checkpoint
yield
def lowercase__ ( ):
__UpperCAmelCase = load_metric(os.path.join('''metrics''' , '''seqeval''' ) )
__UpperCAmelCase = '''ERROR'''
__UpperCAmelCase = F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
with pytest.raises(snake_case_ , match=re.escape(snake_case_ ) ):
metric.compute(predictions=[] , references=[] , scheme=snake_case_ )
| 397 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_lowerCAmelCase = {
'configuration_blip_2': [
'BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP',
'Blip2Config',
'Blip2QFormerConfig',
'Blip2VisionConfig',
],
'processing_blip_2': ['Blip2Processor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCAmelCase = [
'BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST',
'Blip2Model',
'Blip2QFormerModel',
'Blip2PreTrainedModel',
'Blip2ForConditionalGeneration',
'Blip2VisionModel',
]
if TYPE_CHECKING:
from .configuration_blip_a import (
BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlipaConfig,
BlipaQFormerConfig,
BlipaVisionConfig,
)
from .processing_blip_a import BlipaProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blip_a import (
BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST,
BlipaForConditionalGeneration,
BlipaModel,
BlipaPreTrainedModel,
BlipaQFormerModel,
BlipaVisionModel,
)
else:
import sys
_lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 264 |
import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch
import numpy as np
import pytest
from datasets.arrow_dataset import Dataset
from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex
from .utils import require_elasticsearch, require_faiss
__UpperCAmelCase : List[Any] = pytest.mark.integration
@require_faiss
class lowerCamelCase ( SCREAMING_SNAKE_CASE ):
def snake_case_ ( self : Tuple ) -> Tuple:
_a : Tuple = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__snake_case ) for x in np.arange(30 ).tolist()]} )
return dset
def snake_case_ ( self : Optional[Any] ) -> str:
import faiss
_a : Dataset = self._create_dummy_dataset()
_a : Optional[Any] = dset.map(
lambda __snake_case , __snake_case : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__snake_case , keep_in_memory=__snake_case )
_a : List[Any] = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT )
_a , _a : Union[str, Any] = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) )
self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' )
dset.drop_index('''vecs''' )
def snake_case_ ( self : Optional[Any] ) -> str:
import faiss
_a : Dataset = self._create_dummy_dataset()
dset.add_faiss_index_from_external_arrays(
external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , )
_a , _a : int = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) )
self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' )
def snake_case_ ( self : List[Any] ) -> List[str]:
import faiss
_a : Dataset = self._create_dummy_dataset()
dset.add_faiss_index_from_external_arrays(
external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , metric_type=faiss.METRIC_INNER_PRODUCT , )
# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
# see https://bugs.python.org/issue14243 and
# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
with tempfile.NamedTemporaryFile(delete=__snake_case ) as tmp_file:
dset.save_faiss_index('''vecs''' , tmp_file.name )
dset.load_faiss_index('''vecs2''' , tmp_file.name )
os.unlink(tmp_file.name )
_a , _a : Dict = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) )
self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' )
def snake_case_ ( self : Dict ) -> int:
_a : Dataset = self._create_dummy_dataset()
dset.add_faiss_index_from_external_arrays(
external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' )
dset.drop_index('''vecs''' )
self.assertRaises(__snake_case , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) )
def snake_case_ ( self : List[str] ) -> Dict:
from elasticsearch import Elasticsearch
_a : Dataset = self._create_dummy_dataset()
with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch(
'''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk:
_a : int = {'''acknowledged''': True}
mocked_bulk.return_value([(True, None)] * 30 )
_a : Dict = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}}
_a : List[Any] = Elasticsearch()
dset.add_elasticsearch_index('''filename''' , es_client=__snake_case )
_a , _a : Any = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' )
self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' )
@require_faiss
class lowerCamelCase ( SCREAMING_SNAKE_CASE ):
def snake_case_ ( self : str ) -> Any:
import faiss
_a : List[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT )
# add vectors
index.add_vectors(np.eye(5 , dtype=np.floataa ) )
self.assertIsNotNone(index.faiss_index )
self.assertEqual(index.faiss_index.ntotal , 5 )
index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) )
self.assertEqual(index.faiss_index.ntotal , 10 )
# single query
_a : Union[str, Any] = np.zeros(5 , dtype=np.floataa )
_a : Optional[Any] = 1
_a , _a : Optional[int] = index.search(__snake_case )
self.assertRaises(__snake_case , index.search , query.reshape(-1 , 1 ) )
self.assertGreater(scores[0] , 0 )
self.assertEqual(indices[0] , 1 )
# batched queries
_a : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1]
_a , _a : Any = index.search_batch(__snake_case )
self.assertRaises(__snake_case , index.search_batch , queries[0] )
_a : Dict = [scores[0] for scores in total_scores]
_a : Tuple = [indices[0] for indices in total_indices]
self.assertGreater(np.min(__snake_case ) , 0 )
self.assertListEqual([4, 3, 2, 1, 0] , __snake_case )
def snake_case_ ( self : List[str] ) -> int:
import faiss
_a : List[str] = FaissIndex(string_factory='''Flat''' )
index.add_vectors(np.eye(5 , dtype=np.floataa ) )
self.assertIsInstance(index.faiss_index , faiss.IndexFlat )
_a : Union[str, Any] = FaissIndex(string_factory='''LSH''' )
index.add_vectors(np.eye(5 , dtype=np.floataa ) )
self.assertIsInstance(index.faiss_index , faiss.IndexLSH )
with self.assertRaises(__snake_case ):
_a : Optional[Any] = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) )
def snake_case_ ( self : Union[str, Any] ) -> Union[str, Any]:
import faiss
_a : Tuple = faiss.IndexFlat(5 )
_a : Optional[Any] = FaissIndex(custom_index=__snake_case )
index.add_vectors(np.eye(5 , dtype=np.floataa ) )
self.assertIsInstance(index.faiss_index , faiss.IndexFlat )
def snake_case_ ( self : Union[str, Any] ) -> Tuple:
import faiss
_a : List[str] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT )
index.add_vectors(np.eye(5 , dtype=np.floataa ) )
# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
# see https://bugs.python.org/issue14243 and
# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
with tempfile.NamedTemporaryFile(delete=__snake_case ) as tmp_file:
index.save(tmp_file.name )
_a : int = FaissIndex.load(tmp_file.name )
os.unlink(tmp_file.name )
_a : List[Any] = np.zeros(5 , dtype=np.floataa )
_a : List[Any] = 1
_a , _a : List[str] = index.search(__snake_case )
self.assertGreater(scores[0] , 0 )
self.assertEqual(indices[0] , 1 )
@require_faiss
def lowerCamelCase_ ( UpperCamelCase_ ):
import faiss
_a : List[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT )
index.add_vectors(np.eye(5 , dtype=np.floataa ) )
_a : Optional[int] = '''index.faiss'''
_a : List[Any] = f"""mock://{index_name}"""
index.save(UpperCamelCase_ , storage_options=mockfs.storage_options )
_a : str = FaissIndex.load(UpperCamelCase_ , storage_options=mockfs.storage_options )
_a : Union[str, Any] = np.zeros(5 , dtype=np.floataa )
_a : Dict = 1
_a , _a : List[Any] = index.search(UpperCamelCase_ )
assert scores[0] > 0
assert indices[0] == 1
@require_elasticsearch
class lowerCamelCase ( SCREAMING_SNAKE_CASE ):
def snake_case_ ( self : Any ) -> str:
from elasticsearch import Elasticsearch
with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch(
'''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk:
_a : List[Any] = Elasticsearch()
_a : int = {'''acknowledged''': True}
_a : Tuple = ElasticSearchIndex(es_client=__snake_case )
mocked_bulk.return_value([(True, None)] * 3 )
index.add_documents(['''foo''', '''bar''', '''foobar'''] )
# single query
_a : Any = '''foo'''
_a : Union[str, Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}}
_a , _a : Union[str, Any] = index.search(__snake_case )
self.assertEqual(scores[0] , 1 )
self.assertEqual(indices[0] , 0 )
# single query with timeout
_a : List[str] = '''foo'''
_a : Optional[int] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}}
_a , _a : str = index.search(__snake_case , request_timeout=30 )
self.assertEqual(scores[0] , 1 )
self.assertEqual(indices[0] , 0 )
# batched queries
_a : Union[str, Any] = ['''foo''', '''bar''', '''foobar''']
_a : int = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}}
_a , _a : Any = index.search_batch(__snake_case )
_a : Optional[Any] = [scores[0] for scores in total_scores]
_a : List[str] = [indices[0] for indices in total_indices]
self.assertGreater(np.min(__snake_case ) , 0 )
self.assertListEqual([1, 1, 1] , __snake_case )
# batched queries with timeout
_a : Any = ['''foo''', '''bar''', '''foobar''']
_a : List[str] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}}
_a , _a : List[str] = index.search_batch(__snake_case , request_timeout=30 )
_a : Optional[Any] = [scores[0] for scores in total_scores]
_a : str = [indices[0] for indices in total_indices]
self.assertGreater(np.min(__snake_case ) , 0 )
self.assertListEqual([1, 1, 1] , __snake_case )
| 471 | 0 |
from collections import namedtuple
import requests
from lxml import html # type: ignore
lowerCamelCase__ : Any = namedtuple("""covid_data""", """cases deaths recovered""")
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase = "https://www.worldometers.info/coronavirus/" ) -> covid_data:
snake_case__ = '''//div[@class = "maincounter-number"]/span/text()'''
return covid_data(*html.fromstring(requests.get(__lowerCAmelCase ).content ).xpath(__lowerCAmelCase ) )
lowerCamelCase__ : str = """Total COVID-19 cases in the world: {}
Total deaths due to COVID-19 in the world: {}
Total COVID-19 patients recovered in the world: {}"""
print(fmt.format(*covid_stats()))
| 208 |
#
# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
# many nodes) can talk to each other via nccl and allocate gpu memory.
#
# To run first adjust the number of processes and nodes:
#
# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
#
# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
#
# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
#
# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
#
# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# which should tell you what's going on behind the scenes.
#
#
# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
# runs on 2 nodes of 4 gpus per node:
#
# #SBATCH --job-name=test-nodes # name
# #SBATCH --nodes=2 # nodes
# #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node!
# #SBATCH --cpus-per-task=10 # number of cores per tasks
# #SBATCH --gres=gpu:4 # number of gpus
# #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS)
# #SBATCH --output=%x-%j.out # output file name
#
# GPUS_PER_NODE=4
# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
# MASTER_PORT=6000
#
# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
# torch-distributed-gpu-test.py'
#
import fcntl
import os
import socket
import torch
import torch.distributed as dist
def SCREAMING_SNAKE_CASE ( *__lowerCAmelCase ) -> Optional[int]:
with open(__lowerCAmelCase , '''r''' ) as fh:
fcntl.flock(__lowerCAmelCase , fcntl.LOCK_EX )
try:
print(*__lowerCAmelCase )
finally:
fcntl.flock(__lowerCAmelCase , fcntl.LOCK_UN )
lowerCamelCase__ : Dict = int(os.environ["""LOCAL_RANK"""])
torch.cuda.set_device(local_rank)
lowerCamelCase__ : Optional[int] = torch.device("""cuda""", local_rank)
lowerCamelCase__ : str = socket.gethostname()
lowerCamelCase__ : Optional[int] = F"""[{hostname}-{local_rank}]"""
try:
# test distributed
dist.init_process_group("""nccl""")
dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
dist.barrier()
# test cuda is available and can allocate memory
torch.cuda.is_available()
torch.ones(1).cuda(local_rank)
# global rank
lowerCamelCase__ : str = dist.get_rank()
lowerCamelCase__ : Any = dist.get_world_size()
printflock(F"""{gpu} is OK (global rank: {rank}/{world_size})""")
dist.barrier()
if rank == 0:
printflock(F"""pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}""")
except Exception:
printflock(F"""{gpu} is broken""")
raise
| 208 | 1 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from diffusers import (
DDIMScheduler,
KandinskyVaaImgaImgPipeline,
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 ( __snake_case , unittest.TestCase ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE = KandinskyVaaImgaImgPipeline
__SCREAMING_SNAKE_CASE = ["image_embeds", "negative_image_embeds", "image"]
__SCREAMING_SNAKE_CASE = [
"image_embeds",
"negative_image_embeds",
"image",
]
__SCREAMING_SNAKE_CASE = [
"generator",
"height",
"width",
"strength",
"guidance_scale",
"num_inference_steps",
"return_dict",
"guidance_scale",
"num_images_per_prompt",
"output_type",
"return_dict",
]
__SCREAMING_SNAKE_CASE = False
@property
def a ( self ) -> List[Any]:
"""simple docstring"""
return 32
@property
def a ( self ) -> List[str]:
"""simple docstring"""
return 32
@property
def a ( self ) -> int:
"""simple docstring"""
return self.time_input_dim
@property
def a ( self ) -> Optional[Any]:
"""simple docstring"""
return self.time_input_dim * 4
@property
def a ( self ) -> List[Any]:
"""simple docstring"""
return 1_00
@property
def a ( self ) -> int:
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = {
"""in_channels""": 4,
# Out channels is double in channels because predicts mean and variance
"""out_channels""": 8,
"""addition_embed_type""": """image""",
"""down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
"""up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
"""mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
"""block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
"""layers_per_block""": 1,
"""encoder_hid_dim""": self.text_embedder_hidden_size,
"""encoder_hid_dim_type""": """image_proj""",
"""cross_attention_dim""": self.cross_attention_dim,
"""attention_head_dim""": 4,
"""resnet_time_scale_shift""": """scale_shift""",
"""class_embed_type""": None,
}
__snake_case = UNetaDConditionModel(**_A )
return model
@property
def a ( self ) -> Optional[Any]:
"""simple docstring"""
return {
"block_out_channels": [32, 64],
"down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 12,
"out_channels": 3,
"up_block_types": [
"AttnUpDecoderBlock2D",
"UpDecoderBlock2D",
],
"vq_embed_dim": 4,
}
@property
def a ( self ) -> Tuple:
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = VQModel(**self.dummy_movq_kwargs )
return model
def a ( self ) -> Any:
"""simple docstring"""
__snake_case = self.dummy_unet
__snake_case = self.dummy_movq
__snake_case = {
"""num_train_timesteps""": 10_00,
"""beta_schedule""": """linear""",
"""beta_start""": 0.0_0085,
"""beta_end""": 0.012,
"""clip_sample""": False,
"""set_alpha_to_one""": False,
"""steps_offset""": 0,
"""prediction_type""": """epsilon""",
"""thresholding""": False,
}
__snake_case = DDIMScheduler(**_A )
__snake_case = {
"""unet""": unet,
"""scheduler""": scheduler,
"""movq""": movq,
}
return components
def a ( self , _UpperCamelCase , _UpperCamelCase=0 ) -> List[Any]:
"""simple docstring"""
__snake_case = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_A ) ).to(_A )
__snake_case = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(
_A )
# create init_image
__snake_case = floats_tensor((1, 3, 64, 64) , rng=random.Random(_A ) ).to(_A )
__snake_case = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__snake_case = Image.fromarray(np.uinta(_A ) ).convert("""RGB""" ).resize((2_56, 2_56) )
if str(_A ).startswith("""mps""" ):
__snake_case = torch.manual_seed(_A )
else:
__snake_case = torch.Generator(device=_A ).manual_seed(_A )
__snake_case = {
"""image""": init_image,
"""image_embeds""": image_embeds,
"""negative_image_embeds""": negative_image_embeds,
"""generator""": generator,
"""height""": 64,
"""width""": 64,
"""num_inference_steps""": 10,
"""guidance_scale""": 7.0,
"""strength""": 0.2,
"""output_type""": """np""",
}
return inputs
def a ( self ) -> Optional[int]:
"""simple docstring"""
__snake_case = """cpu"""
__snake_case = self.get_dummy_components()
__snake_case = self.pipeline_class(**_A )
__snake_case = pipe.to(_A )
pipe.set_progress_bar_config(disable=_A )
__snake_case = pipe(**self.get_dummy_inputs(_A ) )
__snake_case = output.images
__snake_case = pipe(
**self.get_dummy_inputs(_A ) , return_dict=_A , )[0]
__snake_case = image[0, -3:, -3:, -1]
__snake_case = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
__snake_case = np.array(
[0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263] )
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 ):
"""simple docstring"""
def a ( self ) -> List[Any]:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def a ( self ) -> Optional[Any]:
"""simple docstring"""
__snake_case = load_numpy(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/kandinskyv22/kandinskyv22_img2img_frog.npy""" )
__snake_case = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" )
__snake_case = """A red cartoon frog, 4k"""
__snake_case = KandinskyVaaPriorPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa )
pipe_prior.to(_A )
__snake_case = KandinskyVaaImgaImgPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa )
__snake_case = pipeline.to(_A )
pipeline.set_progress_bar_config(disable=_A )
__snake_case = torch.Generator(device="""cpu""" ).manual_seed(0 )
__snake_case = pipe_prior(
_A , generator=_A , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple()
__snake_case = pipeline(
image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type="""np""" , )
__snake_case = output.images[0]
assert image.shape == (7_68, 7_68, 3)
assert_mean_pixel_difference(_A , _A )
| 268 | """simple docstring"""
from __future__ import absolute_import, division, print_function, unicode_literals
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers import RobertaConfig
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.roberta.modeling_roberta import (
ROBERTA_INPUTS_DOCSTRING,
ROBERTA_START_DOCSTRING,
RobertaEmbeddings,
)
from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy
@add_start_docstrings(
"The RoBERTa Model transformer with early exiting (DeeRoBERTa). " , __snake_case , )
class _snake_case ( __snake_case ):
"""simple docstring"""
a = RobertaConfig
a = "roberta"
def __init__( self : Optional[Any] , _A : Union[str, Any]):
"""simple docstring"""
super().__init__(_A)
_SCREAMING_SNAKE_CASE : Any = RobertaEmbeddings(_A)
self.init_weights()
@add_start_docstrings(
"RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n also takes care of multi-layer training. " , __snake_case , )
class _snake_case ( __snake_case ):
"""simple docstring"""
a = RobertaConfig
a = "roberta"
def __init__( self : Dict , _A : List[str]):
"""simple docstring"""
super().__init__(_A)
_SCREAMING_SNAKE_CASE : List[Any] = config.num_labels
_SCREAMING_SNAKE_CASE : int = config.num_hidden_layers
_SCREAMING_SNAKE_CASE : List[Any] = DeeRobertaModel(_A)
_SCREAMING_SNAKE_CASE : List[str] = nn.Dropout(config.hidden_dropout_prob)
_SCREAMING_SNAKE_CASE : int = nn.Linear(config.hidden_size , self.config.num_labels)
@add_start_docstrings_to_model_forward(_A)
def _lowerCAmelCase ( self : List[Any] , _A : Dict=None , _A : Union[str, Any]=None , _A : List[Any]=None , _A : str=None , _A : Optional[Any]=None , _A : Any=None , _A : Tuple=None , _A : Union[str, Any]=-1 , _A : List[Any]=False , ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : List[str] = self.num_layers
try:
_SCREAMING_SNAKE_CASE : List[Any] = self.roberta(
_A , attention_mask=_A , token_type_ids=_A , position_ids=_A , head_mask=_A , inputs_embeds=_A , )
_SCREAMING_SNAKE_CASE : List[Any] = outputs[1]
_SCREAMING_SNAKE_CASE : Optional[Any] = self.dropout(_A)
_SCREAMING_SNAKE_CASE : List[str] = self.classifier(_A)
_SCREAMING_SNAKE_CASE : Tuple = (logits,) + outputs[2:] # add hidden states and attention if they are here
except HighwayException as e:
_SCREAMING_SNAKE_CASE : Dict = e.message
_SCREAMING_SNAKE_CASE : int = e.exit_layer
_SCREAMING_SNAKE_CASE : str = outputs[0]
if not self.training:
_SCREAMING_SNAKE_CASE : Dict = entropy(_A)
_SCREAMING_SNAKE_CASE : List[str] = []
_SCREAMING_SNAKE_CASE : int = []
if labels is not None:
if self.num_labels == 1:
# We are doing regression
_SCREAMING_SNAKE_CASE : List[str] = MSELoss()
_SCREAMING_SNAKE_CASE : Any = loss_fct(logits.view(-1) , labels.view(-1))
else:
_SCREAMING_SNAKE_CASE : Optional[int] = CrossEntropyLoss()
_SCREAMING_SNAKE_CASE : str = loss_fct(logits.view(-1 , self.num_labels) , labels.view(-1))
# work with highway exits
_SCREAMING_SNAKE_CASE : List[str] = []
for highway_exit in outputs[-1]:
_SCREAMING_SNAKE_CASE : List[Any] = highway_exit[0]
if not self.training:
highway_logits_all.append(_A)
highway_entropy.append(highway_exit[2])
if self.num_labels == 1:
# We are doing regression
_SCREAMING_SNAKE_CASE : str = MSELoss()
_SCREAMING_SNAKE_CASE : Optional[Any] = loss_fct(highway_logits.view(-1) , labels.view(-1))
else:
_SCREAMING_SNAKE_CASE : Tuple = CrossEntropyLoss()
_SCREAMING_SNAKE_CASE : Union[str, Any] = loss_fct(highway_logits.view(-1 , self.num_labels) , labels.view(-1))
highway_losses.append(_A)
if train_highway:
_SCREAMING_SNAKE_CASE : List[str] = (sum(highway_losses[:-1]),) + outputs
# exclude the final highway, of course
else:
_SCREAMING_SNAKE_CASE : Any = (loss,) + outputs
if not self.training:
_SCREAMING_SNAKE_CASE : List[Any] = outputs + ((original_entropy, highway_entropy), exit_layer)
if output_layer >= 0:
_SCREAMING_SNAKE_CASE : Tuple = (
(outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
) # use the highway of the last layer
return outputs # (loss), logits, (hidden_states), (attentions), entropy
| 338 | 0 |
import os
import re
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
'''vocab_file''': '''vocab.txt''',
'''merges_file''': '''bpe.codes''',
}
UpperCamelCase = {
'''vocab_file''': {
'''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt''',
'''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt''',
},
'''merges_file''': {
'''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes''',
'''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes''',
},
}
UpperCamelCase = {
'''vinai/phobert-base''': 2_5_6,
'''vinai/phobert-large''': 2_5_6,
}
def _a ( lowerCamelCase__ ) -> Any:
lowerCamelCase_ : List[Any] = set()
lowerCamelCase_ : Any = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
lowerCamelCase_ : Dict = char
lowerCamelCase_ : List[Any] = set(lowerCamelCase__ )
return pairs
class lowerCamelCase__ ( UpperCAmelCase ):
lowerCamelCase_ : Dict = VOCAB_FILES_NAMES
lowerCamelCase_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP
lowerCamelCase_ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self : Any , _snake_case : Tuple , _snake_case : List[str] , _snake_case : Any="<s>" , _snake_case : int="</s>" , _snake_case : Tuple="</s>" , _snake_case : Optional[int]="<s>" , _snake_case : Tuple="<unk>" , _snake_case : int="<pad>" , _snake_case : Dict="<mask>" , **_snake_case : Any , ) -> List[str]:
"""simple docstring"""
super().__init__(
bos_token=_snake_case , eos_token=_snake_case , unk_token=_snake_case , sep_token=_snake_case , cls_token=_snake_case , pad_token=_snake_case , mask_token=_snake_case , **_snake_case , )
lowerCamelCase_ : str = vocab_file
lowerCamelCase_ : Union[str, Any] = merges_file
lowerCamelCase_ : Optional[int] = {}
lowerCamelCase_ : List[Any] = 0
lowerCamelCase_ : Optional[int] = 1
lowerCamelCase_ : str = 2
lowerCamelCase_ : Tuple = 3
self.add_from_file(_snake_case )
lowerCamelCase_ : str = {v: k for k, v in self.encoder.items()}
with open(_snake_case , encoding='utf-8' ) as merges_handle:
lowerCamelCase_ : int = merges_handle.read().split('\n' )[:-1]
lowerCamelCase_ : int = [tuple(merge.split()[:-1] ) for merge in merges]
lowerCamelCase_ : Optional[int] = dict(zip(_snake_case , range(len(_snake_case ) ) ) )
lowerCamelCase_ : Dict = {}
def UpperCAmelCase_ (self : List[Any] , _snake_case : List[int] , _snake_case : Optional[List[int]] = None ) -> List[int]:
"""simple docstring"""
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowerCamelCase_ : Union[str, Any] = [self.cls_token_id]
lowerCamelCase_ : Union[str, Any] = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def UpperCAmelCase_ (self : Optional[Any] , _snake_case : List[int] , _snake_case : Optional[List[int]] = None , _snake_case : bool = False ) -> List[int]:
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_snake_case , token_ids_a=_snake_case , already_has_special_tokens=_snake_case )
if token_ids_a is None:
return [1] + ([0] * len(_snake_case )) + [1]
return [1] + ([0] * len(_snake_case )) + [1, 1] + ([0] * len(_snake_case )) + [1]
def UpperCAmelCase_ (self : int , _snake_case : List[int] , _snake_case : Optional[List[int]] = None ) -> List[int]:
"""simple docstring"""
lowerCamelCase_ : Tuple = [self.sep_token_id]
lowerCamelCase_ : List[Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def UpperCAmelCase_ (self : Optional[int] ) -> List[str]:
"""simple docstring"""
return len(self.encoder )
def UpperCAmelCase_ (self : int ) -> Optional[int]:
"""simple docstring"""
return dict(self.encoder , **self.added_tokens_encoder )
def UpperCAmelCase_ (self : str , _snake_case : List[Any] ) -> Optional[int]:
"""simple docstring"""
if token in self.cache:
return self.cache[token]
lowerCamelCase_ : List[Any] = tuple(_snake_case )
lowerCamelCase_ : List[str] = tuple(list(word[:-1] ) + [word[-1] + '</w>'] )
lowerCamelCase_ : Union[str, Any] = get_pairs(_snake_case )
if not pairs:
return token
while True:
lowerCamelCase_ : Union[str, Any] = min(_snake_case , key=lambda _snake_case : self.bpe_ranks.get(_snake_case , float('inf' ) ) )
if bigram not in self.bpe_ranks:
break
lowerCamelCase_ , lowerCamelCase_ : Optional[Any] = bigram
lowerCamelCase_ : List[str] = []
lowerCamelCase_ : Dict = 0
while i < len(_snake_case ):
try:
lowerCamelCase_ : int = word.index(_snake_case , _snake_case )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
lowerCamelCase_ : Union[str, Any] = j
if word[i] == first and i < len(_snake_case ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
lowerCamelCase_ : Tuple = tuple(_snake_case )
lowerCamelCase_ : Union[str, Any] = new_word
if len(_snake_case ) == 1:
break
else:
lowerCamelCase_ : Any = get_pairs(_snake_case )
lowerCamelCase_ : str = '@@ '.join(_snake_case )
lowerCamelCase_ : Optional[int] = word[:-4]
lowerCamelCase_ : Optional[Any] = word
return word
def UpperCAmelCase_ (self : int , _snake_case : str ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase_ : Tuple = []
lowerCamelCase_ : Optional[int] = re.findall(R'\S+\n?' , _snake_case )
for token in words:
split_tokens.extend(list(self.bpe(_snake_case ).split(' ' ) ) )
return split_tokens
def UpperCAmelCase_ (self : List[Any] , _snake_case : str ) -> Any:
"""simple docstring"""
return self.encoder.get(_snake_case , self.encoder.get(self.unk_token ) )
def UpperCAmelCase_ (self : Optional[int] , _snake_case : Dict ) -> Any:
"""simple docstring"""
return self.decoder.get(_snake_case , self.unk_token )
def UpperCAmelCase_ (self : str , _snake_case : int ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase_ : Tuple = ' '.join(_snake_case ).replace('@@ ' , '' ).strip()
return out_string
def UpperCAmelCase_ (self : Any , _snake_case : str , _snake_case : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
if not os.path.isdir(_snake_case ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
lowerCamelCase_ : Tuple = os.path.join(
_snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
lowerCamelCase_ : Optional[Any] = os.path.join(
_snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_snake_case ):
copyfile(self.vocab_file , _snake_case )
if os.path.abspath(self.merges_file ) != os.path.abspath(_snake_case ):
copyfile(self.merges_file , _snake_case )
return out_vocab_file, out_merge_file
def UpperCAmelCase_ (self : int , _snake_case : Union[str, Any] ) -> List[str]:
"""simple docstring"""
if isinstance(_snake_case , _snake_case ):
try:
with open(_snake_case , 'r' , encoding='utf-8' ) as fd:
self.add_from_file(_snake_case )
except FileNotFoundError as fnfe:
raise fnfe
except UnicodeError:
raise Exception(f'Incorrect encoding detected in {f}, please rebuild the dataset' )
return
lowerCamelCase_ : Optional[Any] = f.readlines()
for lineTmp in lines:
lowerCamelCase_ : Union[str, Any] = lineTmp.strip()
lowerCamelCase_ : str = line.rfind(' ' )
if idx == -1:
raise ValueError('Incorrect dictionary format, expected \'<token> <cnt>\'' )
lowerCamelCase_ : Optional[Any] = line[:idx]
lowerCamelCase_ : Union[str, Any] = len(self.encoder )
| 144 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = {
'''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''',
# See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox
}
class lowerCamelCase__ ( UpperCAmelCase ):
lowerCamelCase_ : List[str] = 'gpt_neox'
def __init__(self : int , _snake_case : List[str]=5_0432 , _snake_case : List[Any]=6144 , _snake_case : Optional[Any]=44 , _snake_case : Dict=64 , _snake_case : Optional[Any]=2_4576 , _snake_case : str="gelu" , _snake_case : Optional[Any]=0.25 , _snake_case : int=1_0000 , _snake_case : int=0.0 , _snake_case : Any=0.0 , _snake_case : List[str]=0.1 , _snake_case : str=2048 , _snake_case : str=0.02 , _snake_case : Dict=1e-5 , _snake_case : int=True , _snake_case : str=0 , _snake_case : Tuple=2 , _snake_case : Tuple=False , _snake_case : int=True , _snake_case : List[str]=None , **_snake_case : List[str] , ) -> Tuple:
"""simple docstring"""
super().__init__(bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case )
lowerCamelCase_ : Optional[int] = vocab_size
lowerCamelCase_ : Tuple = max_position_embeddings
lowerCamelCase_ : List[str] = hidden_size
lowerCamelCase_ : Optional[Any] = num_hidden_layers
lowerCamelCase_ : Union[str, Any] = num_attention_heads
lowerCamelCase_ : Union[str, Any] = intermediate_size
lowerCamelCase_ : Any = hidden_act
lowerCamelCase_ : Optional[Any] = rotary_pct
lowerCamelCase_ : Tuple = rotary_emb_base
lowerCamelCase_ : List[Any] = attention_dropout
lowerCamelCase_ : int = hidden_dropout
lowerCamelCase_ : List[Any] = classifier_dropout
lowerCamelCase_ : int = initializer_range
lowerCamelCase_ : Dict = layer_norm_eps
lowerCamelCase_ : List[str] = use_cache
lowerCamelCase_ : Dict = tie_word_embeddings
lowerCamelCase_ : int = use_parallel_residual
lowerCamelCase_ : Dict = rope_scaling
self._rope_scaling_validation()
if self.hidden_size % self.num_attention_heads != 0:
raise ValueError(
'The hidden size is not divisble by the number of attention heads! Make sure to update them!' )
def UpperCAmelCase_ (self : Any ) -> Optional[int]:
"""simple docstring"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , _snake_case ) or len(self.rope_scaling ) != 2:
raise ValueError(
'`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '
f'got {self.rope_scaling}' )
lowerCamelCase_ : List[str] = self.rope_scaling.get('type' , _snake_case )
lowerCamelCase_ : Any = self.rope_scaling.get('factor' , _snake_case )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' )
if rope_scaling_factor is None or not isinstance(_snake_case , _snake_case ) or rope_scaling_factor <= 1.0:
raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
| 144 | 1 |
from math import factorial
lowerCAmelCase_ = {str(digit): factorial(digit) for digit in range(10)}
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ):
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise TypeError('''Parameter number must be int''' )
if number < 0:
raise ValueError('''Parameter number must be greater than or equal to 0''' )
# Converts number in string to iterate on its digits and adds its factorial.
return sum(DIGIT_FACTORIAL[digit] for digit in str(SCREAMING_SNAKE_CASE__ ) )
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ = 60 , SCREAMING_SNAKE_CASE__ = 1000000 ):
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
raise TypeError('''Parameters chain_length and number_limit must be int''' )
if chain_length <= 0 or number_limit <= 0:
raise ValueError(
'''Parameters chain_length and number_limit must be greater than 0''' )
# the counter for the chains with the exact desired length
snake_case_ = 0
# the cached sizes of the previous chains
snake_case_ = {}
for start_chain_element in range(1 , SCREAMING_SNAKE_CASE__ ):
# The temporary set will contain the elements of the chain
snake_case_ = set()
snake_case_ = 0
# Stop computing the chain when you find a cached size, a repeating item or the
# length is greater then the desired one.
snake_case_ = start_chain_element
while (
chain_element not in chain_sets_lengths
and chain_element not in chain_set
and chain_set_length <= chain_length
):
chain_set.add(SCREAMING_SNAKE_CASE__ )
chain_set_length += 1
snake_case_ = digit_factorial_sum(SCREAMING_SNAKE_CASE__ )
if chain_element in chain_sets_lengths:
chain_set_length += chain_sets_lengths[chain_element]
snake_case_ = chain_set_length
# If chain contains the exact amount of elements increase the counter
if chain_set_length == chain_length:
chains_counter += 1
return chains_counter
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"""{solution()}""") | 39 |
"""simple docstring"""
from collections import defaultdict
from math import gcd
def __lowercase ( snake_case_ : int = 1500000 ) ->int:
'''simple docstring'''
__A : defaultdict = defaultdict(snake_case_ )
__A : Any = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1 ,snake_case_ ,2 ):
if gcd(snake_case_ ,snake_case_ ) > 1:
continue
__A : List[Any] = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(snake_case_ ,limit + 1 ,snake_case_ ):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1 )
if __name__ == "__main__":
print(f'''{solution() = }''')
| 177 | 0 |
'''simple docstring'''
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DPMSolverMultistepScheduler,
TextToVideoSDPipeline,
UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
@skip_mps
class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase,unittest.TestCase ):
_A = TextToVideoSDPipeline
_A = TEXT_TO_IMAGE_PARAMS
_A = TEXT_TO_IMAGE_BATCH_PARAMS
# No `output_type`.
_A = frozenset(
[
"num_inference_steps",
"generator",
"latents",
"return_dict",
"callback",
"callback_steps",
] )
def __lowerCamelCase ( self ):
"""simple docstring"""
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE_ : str = 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_ : str = DDIMScheduler(
beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=lowercase__ , set_alpha_to_one=lowercase__ , )
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = 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=128 , )
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE_ : Optional[Any] = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=512 , )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = CLIPTextModel(lowercase__ )
SCREAMING_SNAKE_CASE_ : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
SCREAMING_SNAKE_CASE_ : List[Any] = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
}
return components
def __lowerCamelCase ( self , lowercase__ , lowercase__=0 ):
"""simple docstring"""
if str(lowercase__ ).startswith("mps" ):
SCREAMING_SNAKE_CASE_ : Any = torch.manual_seed(lowercase__ )
else:
SCREAMING_SNAKE_CASE_ : List[Any] = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ )
SCREAMING_SNAKE_CASE_ : Optional[int] = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
"output_type": "pt",
}
return inputs
def __lowerCamelCase ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator
SCREAMING_SNAKE_CASE_ : List[Any] = self.get_dummy_components()
SCREAMING_SNAKE_CASE_ : Any = TextToVideoSDPipeline(**lowercase__ )
SCREAMING_SNAKE_CASE_ : str = sd_pipe.to(lowercase__ )
sd_pipe.set_progress_bar_config(disable=lowercase__ )
SCREAMING_SNAKE_CASE_ : Any = self.get_dummy_inputs(lowercase__ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = "np"
SCREAMING_SNAKE_CASE_ : str = sd_pipe(**lowercase__ ).frames
SCREAMING_SNAKE_CASE_ : Optional[int] = frames[0][-3:, -3:, -1]
assert frames[0].shape == (64, 64, 3)
SCREAMING_SNAKE_CASE_ : Tuple = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def __lowerCamelCase ( self ):
"""simple docstring"""
self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowercase__ , expected_max_diff=3e-3 )
@unittest.skipIf(
torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , )
def __lowerCamelCase ( self ):
"""simple docstring"""
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowercase__ , expected_max_diff=1e-2 )
@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." )
def __lowerCamelCase ( self ):
"""simple docstring"""
pass
@unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." )
def __lowerCamelCase ( self ):
"""simple docstring"""
pass
@unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." )
def __lowerCamelCase ( self ):
"""simple docstring"""
pass
def __lowerCamelCase ( self ):
"""simple docstring"""
return super().test_progress_bar()
@slow
@skip_mps
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
def __lowerCamelCase ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy" )
SCREAMING_SNAKE_CASE_ : Dict = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" )
SCREAMING_SNAKE_CASE_ : List[str] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
SCREAMING_SNAKE_CASE_ : Dict = pipe.to("cuda" )
SCREAMING_SNAKE_CASE_ : str = "Spiderman is surfing"
SCREAMING_SNAKE_CASE_ : str = torch.Generator(device="cpu" ).manual_seed(0 )
SCREAMING_SNAKE_CASE_ : Any = pipe(lowercase__ , generator=lowercase__ , num_inference_steps=25 , output_type="pt" ).frames
SCREAMING_SNAKE_CASE_ : List[Any] = video_frames.cpu().numpy()
assert np.abs(expected_video - video ).mean() < 5e-2
def __lowerCamelCase ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy" )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" )
SCREAMING_SNAKE_CASE_ : Dict = pipe.to("cuda" )
SCREAMING_SNAKE_CASE_ : Any = "Spiderman is surfing"
SCREAMING_SNAKE_CASE_ : List[str] = torch.Generator(device="cpu" ).manual_seed(0 )
SCREAMING_SNAKE_CASE_ : int = pipe(lowercase__ , generator=lowercase__ , num_inference_steps=2 , output_type="pt" ).frames
SCREAMING_SNAKE_CASE_ : Dict = video_frames.cpu().numpy()
assert np.abs(expected_video - video ).mean() < 5e-2
| 68 |
'''simple docstring'''
from __future__ import annotations
def __lowerCamelCase ( SCREAMING_SNAKE_CASE_ : int ) -> bool:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[Any] = str(SCREAMING_SNAKE_CASE_ )
return len(SCREAMING_SNAKE_CASE_ ) == 9 and set(SCREAMING_SNAKE_CASE_ ) == set("123456789" )
def __lowerCamelCase ( ) -> int | None:
"""simple docstring"""
for base_num in range(9_9_9_9 , 4_9_9_9 , -1 ):
SCREAMING_SNAKE_CASE_ : int = 1_0_0_0_0_2 * base_num
if is_9_pandigital(SCREAMING_SNAKE_CASE_ ):
return candidate
for base_num in range(3_3_3 , 9_9 , -1 ):
SCREAMING_SNAKE_CASE_ : List[str] = 1_0_0_2_0_0_3 * base_num
if is_9_pandigital(SCREAMING_SNAKE_CASE_ ):
return candidate
return None
if __name__ == "__main__":
print(F'''{solution() = }''')
| 68 | 1 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__ : Optional[int] = {
'google/vit-base-patch16-224': 'https://huggingface.co/vit-base-patch16-224/resolve/main/config.json',
# See all ViT models at https://huggingface.co/models?filter=vit
}
class UpperCamelCase__ (lowerCAmelCase__ ):
'''simple docstring'''
lowerCamelCase_ : Union[str, Any] = """vit"""
def __init__( self , UpperCamelCase__=768 , UpperCamelCase__=12 , UpperCamelCase__=12 , UpperCamelCase__=3072 , UpperCamelCase__="gelu" , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=0.02 , UpperCamelCase__=1e-12 , UpperCamelCase__=224 , UpperCamelCase__=16 , UpperCamelCase__=3 , UpperCamelCase__=True , UpperCamelCase__=16 , **UpperCamelCase__ , ) -> Union[str, Any]:
super().__init__(**UpperCamelCase__ )
lowerCamelCase : Union[str, Any] = hidden_size
lowerCamelCase : List[str] = num_hidden_layers
lowerCamelCase : Union[str, Any] = num_attention_heads
lowerCamelCase : int = intermediate_size
lowerCamelCase : Optional[Any] = hidden_act
lowerCamelCase : int = hidden_dropout_prob
lowerCamelCase : Optional[int] = attention_probs_dropout_prob
lowerCamelCase : List[str] = initializer_range
lowerCamelCase : Optional[int] = layer_norm_eps
lowerCamelCase : List[Any] = image_size
lowerCamelCase : Union[str, Any] = patch_size
lowerCamelCase : Tuple = num_channels
lowerCamelCase : Union[str, Any] = qkv_bias
lowerCamelCase : Union[str, Any] = encoder_stride
class UpperCamelCase__ (lowerCAmelCase__ ):
'''simple docstring'''
lowerCamelCase_ : Any = version.parse("""1.11""" )
@property
def _lowercase ( self ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
] )
@property
def _lowercase ( self ) -> float:
return 1e-4
| 311 |
import random
from .binary_exp_mod import bin_exp_mod
def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=1000 ) -> Optional[int]:
if n < 2:
return False
if n % 2 == 0:
return n == 2
# this means n is odd
lowerCamelCase : Optional[int] = n - 1
lowerCamelCase : int = 0
while d % 2 == 0:
d /= 2
exp += 1
# n - 1=d*(2**exp)
lowerCamelCase : List[str] = 0
while count < prec:
lowerCamelCase : Optional[Any] = random.randint(2 ,n - 1 )
lowerCamelCase : Optional[int] = bin_exp_mod(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
if b != 1:
lowerCamelCase : str = True
for _ in range(_SCREAMING_SNAKE_CASE ):
if b == n - 1:
lowerCamelCase : List[Any] = False
break
lowerCamelCase : Optional[int] = b * b
b %= n
if flag:
return False
count += 1
return True
if __name__ == "__main__":
SCREAMING_SNAKE_CASE__ : Tuple = abs(int(input('Enter bound : ').strip()))
print('Here\'s the list of primes:')
print(', '.join(str(i) for i in range(n + 1) if is_prime_big(i)))
| 311 | 1 |
'''simple docstring'''
import os
from glob import glob
import imageio
import torch
import torchvision
import wandb
from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan
from loaders import load_vqgan
from PIL import Image
from torch import nn
from transformers import CLIPModel, CLIPTokenizerFast
from utils import get_device, get_timestamp, show_pil
class UpperCamelCase__ :
'''simple docstring'''
def __init__( self , SCREAMING_SNAKE_CASE = "cpu" , SCREAMING_SNAKE_CASE = "openai/clip-vit-large-patch14" ) -> None:
__lowerCAmelCase : List[Any] = device
__lowerCAmelCase : str = CLIPTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Tuple = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]
__lowerCAmelCase : str = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]
__lowerCAmelCase : int = torchvision.transforms.Normalize(self.image_mean , self.image_std )
__lowerCAmelCase : Dict = torchvision.transforms.Resize(2_24 )
__lowerCAmelCase : Tuple = torchvision.transforms.CenterCrop(2_24 )
def snake_case ( self , SCREAMING_SNAKE_CASE ) -> List[Any]:
__lowerCAmelCase : List[str] = self.resize(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : List[Any] = self.center_crop(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : int = self.normalize(SCREAMING_SNAKE_CASE )
return images
def __call__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE ) -> Union[str, Any]:
__lowerCAmelCase : Union[str, Any] = self.tokenizer(text=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Tuple = self.preprocess_img(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : List[str] = {key: value.to(self.device ) for (key, value) in encoding.items()}
return encoding
class UpperCamelCase__ ( nn.Module ):
'''simple docstring'''
def __init__( self , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=0.0_1 , 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=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="image" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , ) -> None:
super().__init__()
__lowerCAmelCase : Any = None
__lowerCAmelCase : List[str] = device if device else get_device()
if vqgan:
__lowerCAmelCase : List[str] = vqgan
else:
__lowerCAmelCase : Union[str, Any] = load_vqgan(self.device , conf_path=SCREAMING_SNAKE_CASE , ckpt_path=SCREAMING_SNAKE_CASE )
self.vqgan.eval()
if clip:
__lowerCAmelCase : int = clip
else:
__lowerCAmelCase : Tuple = CLIPModel.from_pretrained('openai/clip-vit-base-patch32' )
self.clip.to(self.device )
__lowerCAmelCase : Any = ProcessorGradientFlow(device=self.device )
__lowerCAmelCase : Optional[int] = iterations
__lowerCAmelCase : List[Any] = lr
__lowerCAmelCase : Union[str, Any] = log
__lowerCAmelCase : Any = make_grid
__lowerCAmelCase : Dict = return_val
__lowerCAmelCase : List[str] = quantize
__lowerCAmelCase : Optional[Any] = self.vqgan.decoder.z_shape
def snake_case ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=True ) -> Optional[Any]:
__lowerCAmelCase : Dict = []
if output_path is None:
__lowerCAmelCase : Optional[Any] = './animation.gif'
if input_path is None:
__lowerCAmelCase : str = self.save_path
__lowerCAmelCase : int = sorted(glob(input_path + '/*' ) )
if not len(SCREAMING_SNAKE_CASE ):
raise ValueError(
'No images found in save path, aborting (did you pass save_intermediate=True to the generate'
' function?)' )
if len(SCREAMING_SNAKE_CASE ) == 1:
print('Only one image found in save path, (did you pass save_intermediate=True to the generate function?)' )
__lowerCAmelCase : Tuple = total_duration / len(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Optional[int] = [frame_duration] * len(SCREAMING_SNAKE_CASE )
if extend_frames:
__lowerCAmelCase : Tuple = 1.5
__lowerCAmelCase : int = 3
for file_name in paths:
if file_name.endswith('.png' ):
images.append(imageio.imread(SCREAMING_SNAKE_CASE ) )
imageio.mimsave(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , duration=SCREAMING_SNAKE_CASE )
print(F"""gif saved to {output_path}""" )
def snake_case ( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None ) -> List[Any]:
if not (path or img):
raise ValueError('Input either path or tensor' )
if img is not None:
raise NotImplementedError
__lowerCAmelCase : List[str] = preprocess(Image.open(SCREAMING_SNAKE_CASE ) , target_image_size=2_56 ).to(self.device )
__lowerCAmelCase : Tuple = preprocess_vqgan(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : List[Any] = self.vqgan.encode(SCREAMING_SNAKE_CASE )
return z
def snake_case ( self , SCREAMING_SNAKE_CASE ) -> str:
__lowerCAmelCase : Optional[Any] = self.latent.detach().requires_grad_()
__lowerCAmelCase : int = base_latent + transform_vector
if self.quantize:
__lowerCAmelCase : List[Any] = self.vqgan.quantize(SCREAMING_SNAKE_CASE )
else:
__lowerCAmelCase : Optional[int] = trans_latent
return self.vqgan.decode(SCREAMING_SNAKE_CASE )
def snake_case ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None ) -> Optional[int]:
__lowerCAmelCase : int = self.clip_preprocessor(text=SCREAMING_SNAKE_CASE , images=SCREAMING_SNAKE_CASE , return_tensors='pt' , padding=SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Optional[Any] = self.clip(**SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Optional[int] = clip_outputs.logits_per_image
if weights is not None:
__lowerCAmelCase : Any = similarity_logits * weights
return similarity_logits.sum()
def snake_case ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]:
__lowerCAmelCase : Optional[int] = self._get_clip_similarity(pos_prompts['prompts'] , SCREAMING_SNAKE_CASE , weights=(1 / pos_prompts['weights']) )
if neg_prompts:
__lowerCAmelCase : str = self._get_clip_similarity(neg_prompts['prompts'] , SCREAMING_SNAKE_CASE , weights=neg_prompts['weights'] )
else:
__lowerCAmelCase : Union[str, Any] = torch.tensor([1] , device=self.device )
__lowerCAmelCase : Union[str, Any] = -torch.log(SCREAMING_SNAKE_CASE ) + torch.log(SCREAMING_SNAKE_CASE )
return loss
def snake_case ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str:
__lowerCAmelCase : Dict = torch.randn_like(self.latent , requires_grad=SCREAMING_SNAKE_CASE , device=self.device )
__lowerCAmelCase : Optional[int] = torch.optim.Adam([vector] , lr=self.lr )
for i in range(self.iterations ):
optim.zero_grad()
__lowerCAmelCase : List[Any] = self._add_vector(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : List[str] = loop_post_process(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Optional[Any] = self._get_CLIP_loss(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
print('CLIP loss' , SCREAMING_SNAKE_CASE )
if self.log:
wandb.log({'CLIP Loss': clip_loss} )
clip_loss.backward(retain_graph=SCREAMING_SNAKE_CASE )
optim.step()
if self.return_val == "image":
yield custom_to_pil(transformed_img[0] )
else:
yield vector
def snake_case ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]:
wandb.init(reinit=SCREAMING_SNAKE_CASE , project='face-editor' )
wandb.config.update({'Positive Prompts': positive_prompts} )
wandb.config.update({'Negative Prompts': negative_prompts} )
wandb.config.update({'lr': self.lr, 'iterations': self.iterations} )
if image_path:
__lowerCAmelCase : Any = Image.open(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : List[Any] = image.resize((2_56, 2_56) )
wandb.log('Original Image' , wandb.Image(SCREAMING_SNAKE_CASE ) )
def snake_case ( self , SCREAMING_SNAKE_CASE ) -> List[str]:
if not prompts:
return []
__lowerCAmelCase : List[str] = []
__lowerCAmelCase : Dict = []
if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
__lowerCAmelCase : Tuple = [prompt.strip() for prompt in prompts.split('|' )]
for prompt in prompts:
if isinstance(SCREAMING_SNAKE_CASE , (tuple, list) ):
__lowerCAmelCase : List[str] = prompt[0]
__lowerCAmelCase : Optional[Any] = float(prompt[1] )
elif ":" in prompt:
__lowerCAmelCase : Optional[Any] = prompt.split(':' )
__lowerCAmelCase : Union[str, Any] = float(SCREAMING_SNAKE_CASE )
else:
__lowerCAmelCase : Union[str, Any] = prompt
__lowerCAmelCase : int = 1.0
processed_prompts.append(SCREAMING_SNAKE_CASE )
weights.append(SCREAMING_SNAKE_CASE )
return {
"prompts": processed_prompts,
"weights": torch.tensor(SCREAMING_SNAKE_CASE , device=self.device ),
}
def snake_case ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , ) -> Dict:
if image_path:
__lowerCAmelCase : Any = self._get_latent(SCREAMING_SNAKE_CASE )
else:
__lowerCAmelCase : Optional[int] = torch.randn(self.latent_dim , device=self.device )
if self.log:
self._init_logging(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
assert pos_prompts, "You must provide at least one positive prompt."
__lowerCAmelCase : Union[str, Any] = self.process_prompts(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Dict = self.process_prompts(SCREAMING_SNAKE_CASE )
if save_final and save_path is None:
__lowerCAmelCase : List[Any] = os.path.join('./outputs/' , '_'.join(pos_prompts['prompts'] ) )
if not os.path.exists(SCREAMING_SNAKE_CASE ):
os.makedirs(SCREAMING_SNAKE_CASE )
else:
__lowerCAmelCase : str = save_path + '_' + get_timestamp()
os.makedirs(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : str = save_path
__lowerCAmelCase : List[Any] = self.vqgan.decode(self.latent )[0]
if show_intermediate:
print('Original Image' )
show_pil(custom_to_pil(SCREAMING_SNAKE_CASE ) )
__lowerCAmelCase : Dict = loop_post_process(SCREAMING_SNAKE_CASE )
for iter, transformed_img in enumerate(self._optimize_CLIP(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ):
if show_intermediate:
show_pil(SCREAMING_SNAKE_CASE )
if save_intermediate:
transformed_img.save(os.path.join(self.save_path , F"""iter_{iter:03d}.png""" ) )
if self.log:
wandb.log({'Image': wandb.Image(SCREAMING_SNAKE_CASE )} )
if show_final:
show_pil(SCREAMING_SNAKE_CASE )
if save_final:
transformed_img.save(os.path.join(self.save_path , F"""iter_{iter:03d}_final.png""" ) )
| 713 |
'''simple docstring'''
from math import factorial
A_ = {str(digit): factorial(digit) for digit in range(10)}
def A ( _UpperCAmelCase : int ) -> int:
'''simple docstring'''
if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ):
raise TypeError('Parameter number must be int' )
if number < 0:
raise ValueError('Parameter number must be greater than or equal to 0' )
# Converts number in string to iterate on its digits and adds its factorial.
return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) )
def A ( _UpperCAmelCase : int = 6_0 ,_UpperCAmelCase : int = 1_0_0_0_0_0_0 ) -> int:
'''simple docstring'''
if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ):
raise TypeError('Parameters chain_length and number_limit must be int' )
if chain_length <= 0 or number_limit <= 0:
raise ValueError(
'Parameters chain_length and number_limit must be greater than 0' )
# the counter for the chains with the exact desired length
__lowerCAmelCase : Any = 0
# the cached sizes of the previous chains
__lowerCAmelCase : dict[int, int] = {}
for start_chain_element in range(1 ,_UpperCAmelCase ):
# The temporary set will contain the elements of the chain
__lowerCAmelCase : Union[str, Any] = set()
__lowerCAmelCase : Union[str, Any] = 0
# Stop computing the chain when you find a cached size, a repeating item or the
# length is greater then the desired one.
__lowerCAmelCase : List[str] = start_chain_element
while (
chain_element not in chain_sets_lengths
and chain_element not in chain_set
and chain_set_length <= chain_length
):
chain_set.add(_UpperCAmelCase )
chain_set_length += 1
__lowerCAmelCase : Optional[Any] = digit_factorial_sum(_UpperCAmelCase )
if chain_element in chain_sets_lengths:
chain_set_length += chain_sets_lengths[chain_element]
__lowerCAmelCase : Any = chain_set_length
# If chain contains the exact amount of elements increase the counter
if chain_set_length == chain_length:
chains_counter += 1
return chains_counter
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F'''{solution()}''')
| 123 | 0 |
def __UpperCamelCase ( A , A , A ):
return round(float(moles / volume ) * nfactor )
def __UpperCamelCase ( A , A , A ):
return round(float((moles * 0.08_21 * temperature) / (volume) ) )
def __UpperCamelCase ( A , A , A ):
return round(float((moles * 0.08_21 * temperature) / (pressure) ) )
def __UpperCamelCase ( A , A , A ):
return round(float((pressure * volume) / (0.08_21 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 415 |
'''simple docstring'''
def snake_case_ ( SCREAMING_SNAKE_CASE__ ):
"""simple docstring"""
return "".join(chr(ord(SCREAMING_SNAKE_CASE__ ) - 32 ) if """a""" <= char <= """z""" else char for char in word )
if __name__ == "__main__":
from doctest import testmod
testmod()
| 533 | 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()
_lowercase = logging.get_logger(__name__)
def UpperCamelCase ( snake_case__):
lowerCAmelCase_ : Optional[Any] = MobileNetVaConfig(layer_norm_eps=0.001)
if "_quant" in model_name:
raise ValueError("Quantized models are not supported.")
lowerCAmelCase_ : Union[str, Any] = re.match(R"^mobilenet_v1_([^_]*)_([^_]*)$" , __UpperCamelCase)
if matches:
lowerCAmelCase_ : str = float(matches[1])
lowerCAmelCase_ : List[str] = int(matches[2])
# The TensorFlow version of MobileNetV1 predicts 1001 classes instead of
# the usual 1000. The first class (index 0) is "background".
lowerCAmelCase_ : str = 10_01
lowerCAmelCase_ : Optional[int] = """imagenet-1k-id2label.json"""
lowerCAmelCase_ : Optional[int] = """huggingface/label-files"""
lowerCAmelCase_ : Optional[int] = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type="dataset") , "r"))
lowerCAmelCase_ : Optional[Any] = {int(__UpperCamelCase) + 1: v for k, v in idalabel.items()}
lowerCAmelCase_ : Dict = """background"""
lowerCAmelCase_ : Any = idalabel
lowerCAmelCase_ : Optional[Any] = {v: k for k, v in idalabel.items()}
return config
def UpperCamelCase ( ):
lowerCAmelCase_ : Tuple = """http://images.cocodataset.org/val2017/000000039769.jpg"""
lowerCAmelCase_ : List[str] = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase).raw)
return im
@torch.no_grad()
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__=False):
lowerCAmelCase_ : List[Any] = get_mobilenet_va_config(__UpperCamelCase)
# Load 🤗 model
lowerCAmelCase_ : int = 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
lowerCAmelCase_ : List[str] = MobileNetVaImageProcessor(
crop_size={"width": config.image_size, "height": config.image_size} , size={"shortest_edge": config.image_size + 32} , )
lowerCAmelCase_ : Dict = image_processor(images=prepare_img() , return_tensors="pt")
lowerCAmelCase_ : Dict = model(**__UpperCamelCase)
lowerCAmelCase_ : List[Any] = outputs.logits
assert logits.shape == (1, 10_01)
if model_name == "mobilenet_v1_1.0_224":
lowerCAmelCase_ : Any = torch.tensor([-4.1_739, -1.1_233, 3.1_205])
elif model_name == "mobilenet_v1_0.75_192":
lowerCAmelCase_ : Any = torch.tensor([-3.9_440, -2.3_141, -0.3_333])
else:
lowerCAmelCase_ : Tuple = 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...")
lowerCAmelCase_ : int = """google/""" + model_name
image_processor.push_to_hub(__UpperCamelCase)
model.push_to_hub(__UpperCamelCase)
if __name__ == "__main__":
_lowercase = 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.'''
)
_lowercase = parser.parse_args()
convert_movilevit_checkpoint(
args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
)
| 721 |
from typing import Any
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ):
_validation(
snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , )
# Creates data structures and fill initial step
lowerCAmelCase_ : dict = {}
lowerCAmelCase_ : dict = {}
for state in states_space:
lowerCAmelCase_ : List[Any] = observations_space[0]
lowerCAmelCase_ : int = (
initial_probabilities[state] * emission_probabilities[state][observation]
)
lowerCAmelCase_ : Dict = None
# Fills the data structure with the probabilities of
# different transitions and pointers to previous states
for o in range(1 , len(snake_case__)):
lowerCAmelCase_ : List[Any] = observations_space[o]
lowerCAmelCase_ : Optional[Any] = observations_space[o - 1]
for state in states_space:
# Calculates the argmax for probability function
lowerCAmelCase_ : List[Any] = ""
lowerCAmelCase_ : Tuple = -1
for k_state in states_space:
lowerCAmelCase_ : int = (
probabilities[(k_state, prior_observation)]
* transition_probabilities[k_state][state]
* emission_probabilities[state][observation]
)
if probability > max_probability:
lowerCAmelCase_ : List[str] = probability
lowerCAmelCase_ : Optional[Any] = k_state
# Update probabilities and pointers dicts
lowerCAmelCase_ : Union[str, Any] = (
probabilities[(arg_max, prior_observation)]
* transition_probabilities[arg_max][state]
* emission_probabilities[state][observation]
)
lowerCAmelCase_ : Any = arg_max
# The final observation
lowerCAmelCase_ : List[Any] = observations_space[len(snake_case__) - 1]
# argmax for given final observation
lowerCAmelCase_ : List[str] = ""
lowerCAmelCase_ : List[str] = -1
for k_state in states_space:
lowerCAmelCase_ : List[str] = probabilities[(k_state, final_observation)]
if probability > max_probability:
lowerCAmelCase_ : List[str] = probability
lowerCAmelCase_ : Tuple = k_state
lowerCAmelCase_ : str = arg_max
# Process pointers backwards
lowerCAmelCase_ : int = last_state
lowerCAmelCase_ : int = []
for o in range(len(snake_case__) - 1 , -1 , -1):
result.append(snake_case__)
lowerCAmelCase_ : Optional[Any] = pointers[previous, observations_space[o]]
result.reverse()
return result
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ):
_validate_not_empty(
snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , )
_validate_lists(snake_case__ , snake_case__)
_validate_dicts(
snake_case__ , snake_case__ , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ):
if not all(
[
observations_space,
states_space,
initial_probabilities,
transition_probabilities,
emission_probabilities,
]):
raise ValueError("There's an empty parameter")
def UpperCamelCase ( snake_case__ , snake_case__):
_validate_list(snake_case__ , "observations_space")
_validate_list(snake_case__ , "states_space")
def UpperCamelCase ( snake_case__ , snake_case__):
if not isinstance(_object , snake_case__):
lowerCAmelCase_ : Optional[Any] = F'''{var_name} must be a list'''
raise ValueError(snake_case__)
else:
for x in _object:
if not isinstance(snake_case__ , snake_case__):
lowerCAmelCase_ : Optional[Any] = F'''{var_name} must be a list of strings'''
raise ValueError(snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , ):
_validate_dict(snake_case__ , "initial_probabilities" , snake_case__)
_validate_nested_dict(snake_case__ , "transition_probabilities")
_validate_nested_dict(snake_case__ , "emission_probabilities")
def UpperCamelCase ( snake_case__ , snake_case__):
_validate_dict(_object , snake_case__ , snake_case__)
for x in _object.values():
_validate_dict(snake_case__ , snake_case__ , snake_case__ , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = False):
if not isinstance(_object , snake_case__):
lowerCAmelCase_ : List[str] = F'''{var_name} must be a dict'''
raise ValueError(snake_case__)
if not all(isinstance(snake_case__ , snake_case__) for x in _object):
lowerCAmelCase_ : Dict = F'''{var_name} all keys must be strings'''
raise ValueError(snake_case__)
if not all(isinstance(snake_case__ , snake_case__) for x in _object.values()):
lowerCAmelCase_ : Union[str, Any] = "nested dictionary " if nested else ""
lowerCAmelCase_ : Any = F'''{var_name} {nested_text}all values must be {value_type.__name__}'''
raise ValueError(snake_case__)
if __name__ == "__main__":
from doctest import testmod
testmod()
| 683 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ = logging.get_logger(__name__)
UpperCamelCase__ = {}
class lowerCamelCase_ ( __a ):
lowerCAmelCase__ = 'llama'
lowerCAmelCase__ = ['past_key_values']
def __init__( self : Optional[int] , _A : Any=32_000 , _A : List[Any]=4_096 , _A : Union[str, Any]=11_008 , _A : Union[str, Any]=32 , _A : List[Any]=32 , _A : List[Any]=None , _A : List[str]="silu" , _A : Tuple=2_048 , _A : Dict=0.0_2 , _A : List[str]=1e-6 , _A : Dict=True , _A : Optional[Any]=0 , _A : Union[str, Any]=1 , _A : Tuple=2 , _A : str=1 , _A : List[Any]=False , _A : Optional[Any]=None , **_A : Dict , ):
'''simple docstring'''
UpperCAmelCase__ : Dict = vocab_size
UpperCAmelCase__ : Optional[int] = max_position_embeddings
UpperCAmelCase__ : Tuple = hidden_size
UpperCAmelCase__ : List[Any] = intermediate_size
UpperCAmelCase__ : Optional[Any] = num_hidden_layers
UpperCAmelCase__ : Dict = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
UpperCAmelCase__ : Optional[int] = num_attention_heads
UpperCAmelCase__ : Any = num_key_value_heads
UpperCAmelCase__ : Optional[Any] = hidden_act
UpperCAmelCase__ : Optional[int] = initializer_range
UpperCAmelCase__ : List[str] = rms_norm_eps
UpperCAmelCase__ : Dict = pretraining_tp
UpperCAmelCase__ : Optional[Any] = use_cache
UpperCAmelCase__ : str = rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A , )
def lowercase_ ( self : Optional[Any] ):
'''simple docstring'''
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , _A ) or len(self.rope_scaling ) != 2:
raise ValueError(
'''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
f"""got {self.rope_scaling}""" )
UpperCAmelCase__ : Union[str, Any] = self.rope_scaling.get('''type''' , _A )
UpperCAmelCase__ : List[str] = self.rope_scaling.get('''factor''' , _A )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" )
if rope_scaling_factor is None or not isinstance(_A , _A ) or rope_scaling_factor <= 1.0:
raise ValueError(f"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
| 75 |
'''simple docstring'''
import re
def snake_case_ ( _lowerCAmelCase : str ) -> str:
if len(re.findall('''[ATCG]''' , _lowerCAmelCase ) ) != len(_lowerCAmelCase ):
raise ValueError('''Invalid Strand''' )
return dna.translate(dna.maketrans('''ATCG''' , '''TAGC''' ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 127 | 0 |
"""simple docstring"""
import argparse
import re
import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SamConfig,
SamImageProcessor,
SamModel,
SamProcessor,
SamVisionConfig,
)
_A = {
"""iou_prediction_head.layers.0""": """iou_prediction_head.proj_in""",
"""iou_prediction_head.layers.1""": """iou_prediction_head.layers.0""",
"""iou_prediction_head.layers.2""": """iou_prediction_head.proj_out""",
"""mask_decoder.output_upscaling.0""": """mask_decoder.upscale_conv1""",
"""mask_decoder.output_upscaling.1""": """mask_decoder.upscale_layer_norm""",
"""mask_decoder.output_upscaling.3""": """mask_decoder.upscale_conv2""",
"""mask_downscaling.0""": """mask_embed.conv1""",
"""mask_downscaling.1""": """mask_embed.layer_norm1""",
"""mask_downscaling.3""": """mask_embed.conv2""",
"""mask_downscaling.4""": """mask_embed.layer_norm2""",
"""mask_downscaling.6""": """mask_embed.conv3""",
"""point_embeddings""": """point_embed""",
"""pe_layer.positional_encoding_gaussian_matrix""": """shared_embedding.positional_embedding""",
"""image_encoder""": """vision_encoder""",
"""neck.0""": """neck.conv1""",
"""neck.1""": """neck.layer_norm1""",
"""neck.2""": """neck.conv2""",
"""neck.3""": """neck.layer_norm2""",
"""patch_embed.proj""": """patch_embed.projection""",
""".norm""": """.layer_norm""",
"""blocks""": """layers""",
}
def lowercase_ ( __UpperCAmelCase ) -> List[str]:
lowerCAmelCase__ : Optional[int] = {}
state_dict.pop("""pixel_mean""" , __UpperCAmelCase )
state_dict.pop("""pixel_std""" , __UpperCAmelCase )
lowerCAmelCase__ : Union[str, Any] = R""".*.output_hypernetworks_mlps.(\d+).layers.(\d+).*"""
for key, value in state_dict.items():
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
if key_to_modify in key:
lowerCAmelCase__ : Optional[Any] = key.replace(__UpperCAmelCase , __UpperCAmelCase )
if re.match(__UpperCAmelCase , __UpperCAmelCase ):
lowerCAmelCase__ : Any = int(re.match(__UpperCAmelCase , __UpperCAmelCase ).group(2 ) )
if layer_nb == 0:
lowerCAmelCase__ : Tuple = key.replace("""layers.0""" , """proj_in""" )
elif layer_nb == 1:
lowerCAmelCase__ : Optional[int] = key.replace("""layers.1""" , """layers.0""" )
elif layer_nb == 2:
lowerCAmelCase__ : Tuple = key.replace("""layers.2""" , """proj_out""" )
lowerCAmelCase__ : Optional[int] = value
lowerCAmelCase__ : List[str] = model_state_dict[
"""prompt_encoder.shared_embedding.positional_embedding"""
]
return model_state_dict
def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase="ybelkada/segment-anything" ) -> int:
lowerCAmelCase__ : List[str] = hf_hub_download(__UpperCAmelCase , f"""checkpoints/{model_name}.pth""" )
if "sam_vit_b" in model_name:
lowerCAmelCase__ : Dict = SamConfig()
elif "sam_vit_l" in model_name:
lowerCAmelCase__ : Optional[int] = SamVisionConfig(
hidden_size=1024 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , )
lowerCAmelCase__ : List[Any] = SamConfig(
vision_config=__UpperCAmelCase , )
elif "sam_vit_h" in model_name:
lowerCAmelCase__ : Union[str, Any] = SamVisionConfig(
hidden_size=1280 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , )
lowerCAmelCase__ : Tuple = SamConfig(
vision_config=__UpperCAmelCase , )
lowerCAmelCase__ : Union[str, Any] = torch.load(__UpperCAmelCase , map_location="""cpu""" )
lowerCAmelCase__ : int = replace_keys(__UpperCAmelCase )
lowerCAmelCase__ : Optional[Any] = SamImageProcessor()
lowerCAmelCase__ : Dict = SamProcessor(image_processor=__UpperCAmelCase )
lowerCAmelCase__ : Dict = SamModel(__UpperCAmelCase )
hf_model.load_state_dict(__UpperCAmelCase )
lowerCAmelCase__ : List[str] = hf_model.to("""cuda""" )
lowerCAmelCase__ : List[str] = """https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"""
lowerCAmelCase__ : Tuple = Image.open(requests.get(__UpperCAmelCase , stream=__UpperCAmelCase ).raw ).convert("""RGB""" )
lowerCAmelCase__ : Tuple = [[[400, 650]]]
lowerCAmelCase__ : Union[str, Any] = [[1]]
lowerCAmelCase__ : Any = processor(images=np.array(__UpperCAmelCase ) , return_tensors="""pt""" ).to("""cuda""" )
with torch.no_grad():
lowerCAmelCase__ : Optional[Any] = hf_model(**__UpperCAmelCase )
lowerCAmelCase__ : Tuple = output.iou_scores.squeeze()
if model_name == "sam_vit_h_4b8939":
assert scores[-1].item() == 0.579890251159668
lowerCAmelCase__ : Dict = processor(
images=np.array(__UpperCAmelCase ) , input_points=__UpperCAmelCase , input_labels=__UpperCAmelCase , return_tensors="""pt""" ).to("""cuda""" )
with torch.no_grad():
lowerCAmelCase__ : Any = hf_model(**__UpperCAmelCase )
lowerCAmelCase__ : Dict = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9712603092193604
lowerCAmelCase__ : Union[str, Any] = ((75, 275, 1725, 850),)
lowerCAmelCase__ : Optional[int] = processor(images=np.array(__UpperCAmelCase ) , input_boxes=__UpperCAmelCase , return_tensors="""pt""" ).to("""cuda""" )
with torch.no_grad():
lowerCAmelCase__ : Optional[Any] = hf_model(**__UpperCAmelCase )
lowerCAmelCase__ : int = output.iou_scores.squeeze()
assert scores[-1].item() == 0.8686015605926514
# Test with 2 points and 1 image.
lowerCAmelCase__ : Tuple = [[[400, 650], [800, 650]]]
lowerCAmelCase__ : Optional[Any] = [[1, 1]]
lowerCAmelCase__ : List[Any] = processor(
images=np.array(__UpperCAmelCase ) , input_points=__UpperCAmelCase , input_labels=__UpperCAmelCase , return_tensors="""pt""" ).to("""cuda""" )
with torch.no_grad():
lowerCAmelCase__ : Tuple = hf_model(**__UpperCAmelCase )
lowerCAmelCase__ : int = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9936047792434692
if __name__ == "__main__":
_A = argparse.ArgumentParser()
_A = ["""sam_vit_b_01ec64""", """sam_vit_h_4b8939""", """sam_vit_l_0b3195"""]
parser.add_argument(
"""--model_name""",
default="""sam_vit_h_4b8939""",
choices=choices,
type=str,
help="""Path to hf config.json of model to convert""",
)
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
parser.add_argument(
"""--push_to_hub""",
action="""store_true""",
help="""Whether to push the model and processor to the hub after converting""",
)
parser.add_argument(
"""--model_hub_id""",
default="""ybelkada/segment-anything""",
choices=choices,
type=str,
help="""Path to hf config.json of model to convert""",
)
_A = parser.parse_args()
convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
| 507 |
"""simple docstring"""
import logging
import os
import quant_trainer
import torch
from torch.utils.data import DataLoader
from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput
_A = logging.getLogger(__name__)
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class _lowerCamelCase ( a_ ):
def __init__( self : List[Any] , *UpperCamelCase : Union[str, Any] , UpperCamelCase : List[str]=None , UpperCamelCase : str=None , UpperCamelCase : Optional[Any]=None , **UpperCamelCase : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
super().__init__(*UpperCamelCase , **UpperCamelCase )
lowerCAmelCase__ : Optional[Any] = eval_examples
lowerCAmelCase__ : List[Any] = post_process_function
lowerCAmelCase__ : Union[str, Any] = quant_trainer_args
lowerCAmelCase__ : Tuple = 1_28 # default number of calibration samples
def _lowerCAmelCase ( self : Union[str, Any] , UpperCamelCase : int=None ) -> List[str]:
"""simple docstring"""
if calib_dataset is None and self.calib_dataset is None:
raise ValueError("""Trainer: calibration requires an calib_dataset.""" )
lowerCAmelCase__ : int = calib_dataset if calib_dataset is not None else self.calib_dataset
lowerCAmelCase__ : Tuple = self._remove_unused_columns(UpperCamelCase , description="""Calibration""" )
return DataLoader(
UpperCamelCase , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=UpperCamelCase , )
def _lowerCAmelCase ( self : int , UpperCamelCase : List[Any]=None ) -> List[Any]:
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = self.train_dataset if calib_dataset is None else calib_dataset
lowerCAmelCase__ : Union[str, Any] = self.get_calib_dataloader(UpperCamelCase )
lowerCAmelCase__ : List[Any] = self.model
quant_trainer.configure_model(UpperCamelCase , self.quant_trainer_args , calib=UpperCamelCase )
model.eval()
quant_trainer.enable_calibration(UpperCamelCase )
logger.info("""***** Running calibration *****""" )
logger.info(f""" Num examples = {self.calib_num}""" )
logger.info(f""" Batch size = {calib_dataloader.batch_size}""" )
for step, inputs in enumerate(UpperCamelCase ):
# Prediction step
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : Tuple = self.prediction_step(UpperCamelCase , UpperCamelCase , prediction_loss_only=UpperCamelCase )
if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
break
quant_trainer.finish_calibration(UpperCamelCase , self.quant_trainer_args )
lowerCAmelCase__ : List[str] = model
def _lowerCAmelCase ( self : Any , UpperCamelCase : Any=None , UpperCamelCase : int=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : str = "eval" ) -> Tuple:
"""simple docstring"""
lowerCAmelCase__ : int = self.eval_dataset if eval_dataset is None else eval_dataset
lowerCAmelCase__ : List[Any] = self.get_eval_dataloader(UpperCamelCase )
lowerCAmelCase__ : str = self.eval_examples if eval_examples is None else eval_examples
# Temporarily disable metric computation, we will do it in the loop here.
lowerCAmelCase__ : str = self.compute_metrics
lowerCAmelCase__ : Tuple = None
lowerCAmelCase__ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
lowerCAmelCase__ : Optional[int] = eval_loop(
UpperCamelCase , description="""Evaluation""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase , )
finally:
lowerCAmelCase__ : int = compute_metrics
if self.post_process_function is not None and self.compute_metrics is not None:
lowerCAmelCase__ : Optional[int] = self.post_process_function(UpperCamelCase , UpperCamelCase , output.predictions )
lowerCAmelCase__ : Union[str, Any] = self.compute_metrics(UpperCamelCase )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
lowerCAmelCase__ : Union[str, Any] = metrics.pop(UpperCamelCase )
self.log(UpperCamelCase )
else:
lowerCAmelCase__ : str = {}
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report() )
lowerCAmelCase__ : Optional[Any] = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCamelCase )
return metrics
def _lowerCAmelCase ( self : List[str] , UpperCamelCase : Any , UpperCamelCase : Dict , UpperCamelCase : Dict=None , UpperCamelCase : str = "test" ) -> int:
"""simple docstring"""
lowerCAmelCase__ : List[str] = self.get_test_dataloader(UpperCamelCase )
# Temporarily disable metric computation, we will do it in the loop here.
lowerCAmelCase__ : List[Any] = self.compute_metrics
lowerCAmelCase__ : int = None
lowerCAmelCase__ : Any = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
try:
lowerCAmelCase__ : Union[str, Any] = eval_loop(
UpperCamelCase , description="""Prediction""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase , )
finally:
lowerCAmelCase__ : str = compute_metrics
if self.post_process_function is None or self.compute_metrics is None:
return output
lowerCAmelCase__ : Tuple = self.post_process_function(UpperCamelCase , UpperCamelCase , output.predictions , """predict""" )
lowerCAmelCase__ : Optional[int] = self.compute_metrics(UpperCamelCase )
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys() ):
if not key.startswith(f"""{metric_key_prefix}_""" ):
lowerCAmelCase__ : Dict = metrics.pop(UpperCamelCase )
return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCamelCase )
def _lowerCAmelCase ( self : Tuple , UpperCamelCase : List[str]="./" ) -> str:
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = self.eval_dataset
lowerCAmelCase__ : Tuple = self.get_eval_dataloader(UpperCamelCase )
lowerCAmelCase__ : Any = next(iter(UpperCamelCase ) )
# saving device - to make it consistent
lowerCAmelCase__ : Tuple = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
# convert to tuple
lowerCAmelCase__ : str = tuple(v.to(UpperCamelCase ) for k, v in batch.items() )
logger.info("""Converting model to be onnx compatible""" )
from pytorch_quantization.nn import TensorQuantizer
lowerCAmelCase__ : Union[str, Any] = True
lowerCAmelCase__ : str = self.model.to(UpperCamelCase )
model.eval()
model.float()
lowerCAmelCase__ : List[Any] = model.module if hasattr(UpperCamelCase , """module""" ) else model
quant_trainer.configure_model(UpperCamelCase , self.quant_trainer_args )
lowerCAmelCase__ : int = os.path.join(UpperCamelCase , """model.onnx""" )
logger.info(f"""exporting model to {output_model_file}""" )
lowerCAmelCase__ : Union[str, Any] = {0: """batch_size""", 1: """seq_len"""}
torch.onnx.export(
UpperCamelCase , UpperCamelCase , UpperCamelCase , export_params=UpperCamelCase , opset_version=13 , do_constant_folding=UpperCamelCase , input_names=["""input_ids""", """attention_mask""", """token_type_ids"""] , output_names=["""output_start_logits""", """output_end_logits"""] , dynamic_axes={
"""input_ids""": axes,
"""attention_mask""": axes,
"""token_type_ids""": axes,
"""output_start_logits""": axes,
"""output_end_logits""": axes,
} , verbose=UpperCamelCase , )
logger.info("""onnx export finished""" )
| 507 | 1 |
import gc
import random
import tempfile
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMInverseScheduler,
DDIMScheduler,
DPMSolverMultistepInverseScheduler,
DPMSolverMultistepScheduler,
StableDiffusionDiffEditPipeline,
UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device
from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class lowerCamelCase_ ( _lowercase , _lowercase , unittest.TestCase ):
_lowercase : Tuple = StableDiffusionDiffEditPipeline
_lowercase : Optional[Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''}
_lowercase : Union[str, Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''}
_lowercase : Optional[int] = frozenset(
[] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
_lowercase : List[Any] = frozenset([] )
def lowerCAmelCase_ ( self : List[str] ):
torch.manual_seed(0 )
__A : Optional[Any] = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__A , )
__A : Dict = DDIMScheduler(
beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=__A , set_alpha_to_one=__A , )
__A : Union[str, Any] = DDIMInverseScheduler(
beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=__A , set_alpha_to_zero=__A , )
torch.manual_seed(0 )
__A : Tuple = 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=128 , )
torch.manual_seed(0 )
__A : Tuple = 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=1000 , hidden_act="""gelu""" , projection_dim=512 , )
__A : Optional[Any] = CLIPTextModel(__A )
__A : Union[str, Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
__A : str = {
"""unet""": unet,
"""scheduler""": scheduler,
"""inverse_scheduler""": inverse_scheduler,
"""vae""": vae,
"""text_encoder""": text_encoder,
"""tokenizer""": tokenizer,
"""safety_checker""": None,
"""feature_extractor""": None,
}
return components
def lowerCAmelCase_ ( self : Any , __A : List[str] , __A : List[Any]=0 ):
__A : Optional[Any] = floats_tensor((1, 16, 16) , rng=random.Random(__A ) ).to(__A )
__A : Optional[Any] = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(__A ) ).to(__A )
if str(__A ).startswith("""mps""" ):
__A : Dict = torch.manual_seed(__A )
else:
__A : Tuple = torch.Generator(device=__A ).manual_seed(__A )
__A : Tuple = {
"""prompt""": """a dog and a newt""",
"""mask_image""": mask,
"""image_latents""": latents,
"""generator""": generator,
"""num_inference_steps""": 2,
"""inpaint_strength""": 1.0,
"""guidance_scale""": 6.0,
"""output_type""": """numpy""",
}
return inputs
def lowerCAmelCase_ ( self : Union[str, Any] , __A : int , __A : List[str]=0 ):
__A : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A )
__A : int = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__A : int = Image.fromarray(np.uinta(__A ) ).convert("""RGB""" )
if str(__A ).startswith("""mps""" ):
__A : Any = torch.manual_seed(__A )
else:
__A : Union[str, Any] = torch.Generator(device=__A ).manual_seed(__A )
__A : Optional[int] = {
"""image""": image,
"""source_prompt""": """a cat and a frog""",
"""target_prompt""": """a dog and a newt""",
"""generator""": generator,
"""num_inference_steps""": 2,
"""num_maps_per_mask""": 2,
"""mask_encode_strength""": 1.0,
"""guidance_scale""": 6.0,
"""output_type""": """numpy""",
}
return inputs
def lowerCAmelCase_ ( self : int , __A : str , __A : List[Any]=0 ):
__A : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A )
__A : int = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__A : Dict = Image.fromarray(np.uinta(__A ) ).convert("""RGB""" )
if str(__A ).startswith("""mps""" ):
__A : List[str] = torch.manual_seed(__A )
else:
__A : Any = torch.Generator(device=__A ).manual_seed(__A )
__A : int = {
"""image""": image,
"""prompt""": """a cat and a frog""",
"""generator""": generator,
"""num_inference_steps""": 2,
"""inpaint_strength""": 1.0,
"""guidance_scale""": 6.0,
"""decode_latents""": True,
"""output_type""": """numpy""",
}
return inputs
def lowerCAmelCase_ ( self : Dict ):
if not hasattr(self.pipeline_class , """_optional_components""" ):
return
__A : Tuple = self.get_dummy_components()
__A : Tuple = self.pipeline_class(**__A )
pipe.to(__A )
pipe.set_progress_bar_config(disable=__A )
# set all optional components to None and update pipeline config accordingly
for optional_component in pipe._optional_components:
setattr(__A , __A , __A )
pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} )
__A : Optional[int] = self.get_dummy_inputs(__A )
__A : str = pipe(**__A )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(__A )
__A : str = self.pipeline_class.from_pretrained(__A )
pipe_loaded.to(__A )
pipe_loaded.set_progress_bar_config(disable=__A )
for optional_component in pipe._optional_components:
self.assertTrue(
getattr(__A , __A ) is None , F"""`{optional_component}` did not stay set to None after loading.""" , )
__A : int = self.get_dummy_inputs(__A )
__A : List[Any] = pipe_loaded(**__A )[0]
__A : str = np.abs(output - output_loaded ).max()
self.assertLess(__A , 1e-4 )
def lowerCAmelCase_ ( self : List[Any] ):
__A : str = """cpu"""
__A : int = self.get_dummy_components()
__A : Any = self.pipeline_class(**__A )
pipe.to(__A )
pipe.set_progress_bar_config(disable=__A )
__A : Dict = self.get_dummy_mask_inputs(__A )
__A : int = pipe.generate_mask(**__A )
__A : Optional[Any] = mask[0, -3:, -3:]
self.assertEqual(mask.shape , (1, 16, 16) )
__A : List[Any] = np.array([0] * 9 )
__A : str = np.abs(mask_slice.flatten() - expected_slice ).max()
self.assertLessEqual(__A , 1e-3 )
self.assertEqual(mask[0, -3, -4] , 0 )
def lowerCAmelCase_ ( self : int ):
__A : int = """cpu"""
__A : List[Any] = self.get_dummy_components()
__A : Optional[int] = self.pipeline_class(**__A )
pipe.to(__A )
pipe.set_progress_bar_config(disable=__A )
__A : Any = self.get_dummy_inversion_inputs(__A )
__A : List[str] = pipe.invert(**__A ).images
__A : List[Any] = image[0, -1, -3:, -3:]
self.assertEqual(image.shape , (2, 32, 32, 3) )
__A : int = np.array(
[0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] , )
__A : Optional[int] = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(__A , 1e-3 )
def lowerCAmelCase_ ( self : Optional[Any] ):
super().test_inference_batch_single_identical(expected_max_diff=5e-3 )
def lowerCAmelCase_ ( self : List[Any] ):
__A : Union[str, Any] = """cpu"""
__A : Optional[Any] = self.get_dummy_components()
__A : Dict = {"""beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """beta_schedule""": """scaled_linear"""}
__A : Optional[int] = DPMSolverMultistepScheduler(**__A )
__A : Dict = DPMSolverMultistepInverseScheduler(**__A )
__A : List[Any] = self.pipeline_class(**__A )
pipe.to(__A )
pipe.set_progress_bar_config(disable=__A )
__A : Union[str, Any] = self.get_dummy_inversion_inputs(__A )
__A : Optional[int] = pipe.invert(**__A ).images
__A : Any = image[0, -1, -3:, -3:]
self.assertEqual(image.shape , (2, 32, 32, 3) )
__A : int = np.array(
[0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] , )
__A : int = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(__A , 1e-3 )
@require_torch_gpu
@slow
class lowerCamelCase_ ( unittest.TestCase ):
def lowerCAmelCase_ ( self : str ):
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@classmethod
def lowerCAmelCase_ ( cls : str ):
__A : Dict = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""" )
__A : Any = raw_image.convert("""RGB""" ).resize((768, 768) )
__A : Dict = raw_image
def lowerCAmelCase_ ( self : List[str] ):
__A : List[str] = torch.manual_seed(0 )
__A : Any = StableDiffusionDiffEditPipeline.from_pretrained(
"""stabilityai/stable-diffusion-2-1""" , safety_checker=__A , torch_dtype=torch.floataa )
__A : int = DDIMScheduler.from_config(pipe.scheduler.config )
__A : List[str] = DDIMInverseScheduler.from_config(pipe.scheduler.config )
pipe.enable_model_cpu_offload()
pipe.set_progress_bar_config(disable=__A )
__A : Optional[int] = """a bowl of fruit"""
__A : int = """a bowl of pears"""
__A : Any = pipe.generate_mask(
image=self.raw_image , source_prompt=__A , target_prompt=__A , generator=__A , )
__A : List[Any] = pipe.invert(
prompt=__A , image=self.raw_image , inpaint_strength=0.7 , generator=__A ).latents
__A : Optional[int] = pipe(
prompt=__A , mask_image=__A , image_latents=__A , generator=__A , negative_prompt=__A , inpaint_strength=0.7 , output_type="""numpy""" , ).images[0]
__A : Dict = (
np.array(
load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/diffedit/pears.png""" ).resize((768, 768) ) )
/ 255
)
assert np.abs((expected_image - image).max() ) < 5e-1
def lowerCAmelCase_ ( self : Union[str, Any] ):
__A : Tuple = torch.manual_seed(0 )
__A : Optional[Any] = StableDiffusionDiffEditPipeline.from_pretrained(
"""stabilityai/stable-diffusion-2-1""" , safety_checker=__A , torch_dtype=torch.floataa )
__A : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
__A : str = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config )
pipe.enable_model_cpu_offload()
pipe.set_progress_bar_config(disable=__A )
__A : Any = """a bowl of fruit"""
__A : List[str] = """a bowl of pears"""
__A : Any = pipe.generate_mask(
image=self.raw_image , source_prompt=__A , target_prompt=__A , generator=__A , )
__A : Optional[Any] = pipe.invert(
prompt=__A , image=self.raw_image , inpaint_strength=0.7 , generator=__A , num_inference_steps=25 , ).latents
__A : Optional[Any] = pipe(
prompt=__A , mask_image=__A , image_latents=__A , generator=__A , negative_prompt=__A , inpaint_strength=0.7 , num_inference_steps=25 , output_type="""numpy""" , ).images[0]
__A : Dict = (
np.array(
load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/diffedit/pears.png""" ).resize((768, 768) ) )
/ 255
)
assert np.abs((expected_image - image).max() ) < 5e-1
| 17 |
"""simple docstring"""
__snake_case = """ABCDEFGHIJKLMNOPQRSTUVWXYZ"""
def __lowerCAmelCase ( ) -> None:
"""simple docstring"""
snake_case : str = input("Enter message: " )
snake_case : Tuple = input("Enter key [alphanumeric]: " )
snake_case : Union[str, Any] = input("Encrypt/Decrypt [e/d]: " )
if mode.lower().startswith("e" ):
snake_case : str = "encrypt"
snake_case : Optional[int] = encrypt_message(lowercase , lowercase )
elif mode.lower().startswith("d" ):
snake_case : List[Any] = "decrypt"
snake_case : Tuple = decrypt_message(lowercase , lowercase )
print(F'\n{mode.title()}ed message:' )
print(lowercase )
def __lowerCAmelCase ( lowercase : str , lowercase : str ) -> str:
"""simple docstring"""
return translate_message(lowercase , lowercase , "encrypt" )
def __lowerCAmelCase ( lowercase : str , lowercase : str ) -> str:
"""simple docstring"""
return translate_message(lowercase , lowercase , "decrypt" )
def __lowerCAmelCase ( lowercase : str , lowercase : str , lowercase : str ) -> str:
"""simple docstring"""
snake_case : List[Any] = []
snake_case : List[str] = 0
snake_case : List[Any] = key.upper()
for symbol in message:
snake_case : Optional[int] = LETTERS.find(symbol.upper() )
if num != -1:
if mode == "encrypt":
num += LETTERS.find(key[key_index] )
elif mode == "decrypt":
num -= LETTERS.find(key[key_index] )
num %= len(lowercase )
if symbol.isupper():
translated.append(LETTERS[num] )
elif symbol.islower():
translated.append(LETTERS[num].lower() )
key_index += 1
if key_index == len(lowercase ):
snake_case : List[str] = 0
else:
translated.append(lowercase )
return "".join(lowercase )
if __name__ == "__main__":
main()
| 178 | 0 |
import unittest
import numpy as np
from transformers.testing_utils import require_pytesseract, require_torch
from transformers.utils import is_pytesseract_available, is_torch_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_pytesseract_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=18 , lowerCamelCase=30 , lowerCamelCase=4_00 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , ):
snake_case__ = size if size is not None else {"height": 18, "width": 18}
snake_case__ = parent
snake_case__ = batch_size
snake_case__ = num_channels
snake_case__ = image_size
snake_case__ = min_resolution
snake_case__ = max_resolution
snake_case__ = do_resize
snake_case__ = size
snake_case__ = apply_ocr
def A_ ( self ):
return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr}
@require_torch
@require_pytesseract
class _SCREAMING_SNAKE_CASE ( __UpperCamelCase , unittest.TestCase ):
_A : Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None
def A_ ( self ):
snake_case__ = LayoutLMvaImageProcessingTester(self )
@property
def A_ ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def A_ ( self ):
snake_case__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) )
self.assertTrue(hasattr(lowerCamelCase , "size" ) )
self.assertTrue(hasattr(lowerCamelCase , "apply_ocr" ) )
def A_ ( self ):
snake_case__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"height": 18, "width": 18} )
snake_case__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {"height": 42, "width": 42} )
def A_ ( self ):
pass
def A_ ( self ):
# Initialize image_processing
snake_case__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
snake_case__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(lowerCamelCase , Image.Image )
# Test not batched input
snake_case__ = image_processing(image_inputs[0] , return_tensors="pt" )
self.assertEqual(
encoding.pixel_values.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["height"],
self.image_processor_tester.size["width"],
) , )
self.assertIsInstance(encoding.words , lowerCamelCase )
self.assertIsInstance(encoding.boxes , lowerCamelCase )
# Test batched
snake_case__ = image_processing(lowerCamelCase , 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.size["height"],
self.image_processor_tester.size["width"],
) , )
def A_ ( self ):
# Initialize image_processing
snake_case__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
snake_case__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(lowerCamelCase , np.ndarray )
# Test not batched input
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.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
snake_case__ = image_processing(lowerCamelCase , 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.size["height"],
self.image_processor_tester.size["width"],
) , )
def A_ ( self ):
# Initialize image_processing
snake_case__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
snake_case__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase )
for image in image_inputs:
self.assertIsInstance(lowerCamelCase , torch.Tensor )
# Test not batched input
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.size["height"],
self.image_processor_tester.size["width"],
) , )
# Test batched
snake_case__ = image_processing(lowerCamelCase , 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.size["height"],
self.image_processor_tester.size["width"],
) , )
def A_ ( self ):
# with apply_OCR = True
snake_case__ = LayoutLMvaImageProcessor()
from datasets import load_dataset
snake_case__ = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" )
snake_case__ = Image.open(ds[0]["file"] ).convert("RGB" )
snake_case__ = image_processing(lowerCamelCase , return_tensors="pt" )
self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
self.assertEqual(len(encoding.words ) , len(encoding.boxes ) )
# fmt: off
# the words and boxes were obtained with Tesseract 4.1.1
snake_case__ = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231
snake_case__ = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231
# fmt: on
self.assertListEqual(encoding.words , lowerCamelCase )
self.assertListEqual(encoding.boxes , lowerCamelCase )
# with apply_OCR = False
snake_case__ = LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase )
snake_case__ = image_processing(lowerCamelCase , return_tensors="pt" )
self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
| 530 |
def SCREAMING_SNAKE_CASE__ ( __lowerCAmelCase , __lowerCAmelCase ):
return price * (1 + tax_rate)
if __name__ == "__main__":
print(F'''{price_plus_tax(100, 0.2_5) = }''')
print(F'''{price_plus_tax(1_2_5.5_0, 0.0_5) = }''')
| 530 | 1 |
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
HubertConfig,
HubertForCTC,
HubertModel,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
A : Tuple = logging.get_logger(__name__)
A : Optional[int] = {
'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',
'w2v_model.layer_norm': 'feature_projection.layer_norm',
'w2v_encoder.proj': 'lm_head',
'mask_emb': 'masked_spec_embed',
}
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]:
'''simple docstring'''
for attribute in key.split("." ):
__snake_case = getattr(_lowerCAmelCase , _lowerCAmelCase )
if weight_type is not None:
__snake_case = getattr(_lowerCAmelCase , _lowerCAmelCase ).shape
else:
__snake_case = hf_pointer.shape
assert hf_shape == value.shape, (
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":
__snake_case = value
elif weight_type == "weight_g":
__snake_case = value
elif weight_type == "weight_v":
__snake_case = value
elif weight_type == "bias":
__snake_case = value
else:
__snake_case = value
logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' )
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Tuple:
'''simple docstring'''
__snake_case = []
__snake_case = fairseq_model.state_dict()
__snake_case = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor
for name, value in fairseq_dict.items():
__snake_case = False
if "conv_layers" in name:
load_conv_layer(
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , hf_model.config.feat_extract_norm == "group" , )
__snake_case = True
else:
for key, mapped_key in MAPPING.items():
__snake_case = "hubert." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key
if key in name or (key.split("w2v_model." )[-1] == name.split("." )[0] and not is_finetuned):
__snake_case = True
if "*" in mapped_key:
__snake_case = name.split(_lowerCAmelCase )[0].split("." )[-2]
__snake_case = mapped_key.replace("*" , _lowerCAmelCase )
if "weight_g" in name:
__snake_case = "weight_g"
elif "weight_v" in name:
__snake_case = "weight_v"
elif "weight" in name:
__snake_case = "weight"
elif "bias" in name:
__snake_case = "bias"
else:
__snake_case = None
set_recursively(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
continue
if not is_used:
unused_weights.append(_lowerCAmelCase )
logger.warning(F'''Unused weights: {unused_weights}''' )
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]:
'''simple docstring'''
__snake_case = full_name.split("conv_layers." )[-1]
__snake_case = name.split("." )
__snake_case = int(items[0] )
__snake_case = int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
)
__snake_case = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
)
__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:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
" found."
)
__snake_case = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
)
__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 ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=True ) -> List[str]:
'''simple docstring'''
if config_path is not None:
__snake_case = HubertConfig.from_pretrained(_lowerCAmelCase )
else:
__snake_case = HubertConfig()
if is_finetuned:
if dict_path:
__snake_case = Dictionary.load(_lowerCAmelCase )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
__snake_case = target_dict.pad_index
__snake_case = target_dict.bos_index
__snake_case = target_dict.eos_index
__snake_case = len(target_dict.symbols )
__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 )
with open(_lowerCAmelCase , "w" , encoding="utf-8" ) as vocab_handle:
json.dump(target_dict.indices , _lowerCAmelCase )
__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 , )
__snake_case = True if config.feat_extract_norm == "layer" else False
__snake_case = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=_lowerCAmelCase , return_attention_mask=_lowerCAmelCase , )
__snake_case = WavaVecaProcessor(feature_extractor=_lowerCAmelCase , tokenizer=_lowerCAmelCase )
processor.save_pretrained(_lowerCAmelCase )
__snake_case = HubertForCTC(_lowerCAmelCase )
else:
__snake_case = HubertModel(_lowerCAmelCase )
if is_finetuned:
__snake_case , __snake_case , __snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} )
else:
__snake_case , __snake_case , __snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] )
__snake_case = model[0].eval()
recursively_load_weights(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
hf_wavavec.save_pretrained(_lowerCAmelCase )
if __name__ == "__main__":
A : Optional[Any] = 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'
)
A : List[str] = parser.parse_args()
convert_hubert_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 371 |
# flake8: noqa
# Lint as: python3
from typing import Dict, List, Optional, Type
from .. import config
from ..utils import logging
from .formatting import (
ArrowFormatter,
CustomFormatter,
Formatter,
PandasFormatter,
PythonFormatter,
TensorFormatter,
format_table,
query_table,
)
from .np_formatter import NumpyFormatter
A : Union[str, Any] = logging.get_logger(__name__)
A : Dict[Optional[str], Type[Formatter]] = {}
A : Dict[Optional[str], str] = {}
A : Dict[Optional[str], Exception] = {}
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , ) -> str:
'''simple docstring'''
__snake_case = aliases if aliases is not None else []
if format_type in _FORMAT_TYPES:
logger.warning(
F'''Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})''' )
__snake_case = formatter_cls
for alias in set(aliases + [format_type] ):
if alias in _FORMAT_TYPES_ALIASES:
logger.warning(
F'''Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})''' )
__snake_case = format_type
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None ) -> List[Any]:
'''simple docstring'''
__snake_case = aliases if aliases is not None else []
for alias in set(aliases + [format_type] ):
__snake_case = unavailable_error
# Here we define all the available formatting functions that can be used by `Dataset.set_format`
_register_formatter(PythonFormatter, None, aliases=['python'])
_register_formatter(ArrowFormatter, 'arrow', aliases=['pa', 'pyarrow'])
_register_formatter(NumpyFormatter, 'numpy', aliases=['np'])
_register_formatter(PandasFormatter, 'pandas', aliases=['pd'])
_register_formatter(CustomFormatter, 'custom')
if config.TORCH_AVAILABLE:
from .torch_formatter import TorchFormatter
_register_formatter(TorchFormatter, 'torch', aliases=['pt', 'pytorch'])
else:
A : Any = ValueError('PyTorch needs to be installed to be able to return PyTorch tensors.')
_register_unavailable_formatter(_torch_error, 'torch', aliases=['pt', 'pytorch'])
if config.TF_AVAILABLE:
from .tf_formatter import TFFormatter
_register_formatter(TFFormatter, 'tensorflow', aliases=['tf'])
else:
A : Tuple = ValueError('Tensorflow needs to be installed to be able to return Tensorflow tensors.')
_register_unavailable_formatter(_tf_error, 'tensorflow', aliases=['tf'])
if config.JAX_AVAILABLE:
from .jax_formatter import JaxFormatter
_register_formatter(JaxFormatter, 'jax', aliases=[])
else:
A : Optional[int] = ValueError('JAX needs to be installed to be able to return JAX arrays.')
_register_unavailable_formatter(_jax_error, 'jax', aliases=[])
def _lowerCAmelCase ( _lowerCAmelCase ) -> Optional[str]:
'''simple docstring'''
if format_type in _FORMAT_TYPES_ALIASES:
return _FORMAT_TYPES_ALIASES[format_type]
else:
return format_type
def _lowerCAmelCase ( _lowerCAmelCase , **_lowerCAmelCase ) -> Formatter:
'''simple docstring'''
__snake_case = get_format_type_from_alias(_lowerCAmelCase )
if format_type in _FORMAT_TYPES:
return _FORMAT_TYPES[format_type](**_lowerCAmelCase )
if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE:
raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type]
else:
raise ValueError(
F'''Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got \'{format_type}\'''' )
| 371 | 1 |
import argparse
import os
import re
__A : Optional[Any] = 'src/diffusers'
# Pattern that looks at the indentation in a line.
__A : int = re.compile(R'^(\s*)\S')
# Pattern that matches `"key":" and puts `key` in group 0.
__A : Dict = re.compile(R'^\s*"([^"]+)":')
# Pattern that matches `_import_structure["key"]` and puts `key` in group 0.
__A : Optional[Any] = re.compile(R'^\s*_import_structure\["([^"]+)"\]')
# Pattern that matches `"key",` and puts `key` in group 0.
__A : int = re.compile(R'^\s*"([^"]+)",\s*$')
# Pattern that matches any `[stuff]` and puts `stuff` in group 0.
__A : Optional[Any] = re.compile(R'\[([^\]]+)\]')
def __UpperCamelCase ( _A : int ) ->Dict:
"""simple docstring"""
lowerCamelCase_ =_re_indent.search(_A )
return "" if search is None else search.groups()[0]
def __UpperCamelCase ( _A : Optional[Any] , _A : Optional[int]="" , _A : int=None , _A : List[str]=None ) ->List[Any]:
"""simple docstring"""
lowerCamelCase_ =0
lowerCamelCase_ =code.split("""\n""" )
if start_prompt is not None:
while not lines[index].startswith(_A ):
index += 1
lowerCamelCase_ =["""\n""".join(lines[:index] )]
else:
lowerCamelCase_ =[]
# We split into blocks until we get to the `end_prompt` (or the end of the block).
lowerCamelCase_ =[lines[index]]
index += 1
while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )):
if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level:
if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ):
current_block.append(lines[index] )
blocks.append("""\n""".join(_A ) )
if index < len(_A ) - 1:
lowerCamelCase_ =[lines[index + 1]]
index += 1
else:
lowerCamelCase_ =[]
else:
blocks.append("""\n""".join(_A ) )
lowerCamelCase_ =[lines[index]]
else:
current_block.append(lines[index] )
index += 1
# Adds current block if it's nonempty.
if len(_A ) > 0:
blocks.append("""\n""".join(_A ) )
# Add final block after end_prompt if provided.
if end_prompt is not None and index < len(_A ):
blocks.append("""\n""".join(lines[index:] ) )
return blocks
def __UpperCamelCase ( _A : Optional[int] ) ->Optional[int]:
"""simple docstring"""
def _inner(_A : Optional[Any] ):
return key(_A ).lower().replace("""_""" , """""" )
return _inner
def __UpperCamelCase ( _A : int , _A : List[Any]=None ) ->List[str]:
"""simple docstring"""
# If no key is provided, we use a noop.
def noop(_A : List[str] ):
return x
if key is None:
lowerCamelCase_ =noop
# Constants are all uppercase, they go first.
lowerCamelCase_ =[obj for obj in objects if key(_A ).isupper()]
# Classes are not all uppercase but start with a capital, they go second.
lowerCamelCase_ =[obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()]
# Functions begin with a lowercase, they go last.
lowerCamelCase_ =[obj for obj in objects if not key(_A )[0].isupper()]
lowerCamelCase_ =ignore_underscore(_A )
return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A )
def __UpperCamelCase ( _A : List[str] ) ->List[str]:
"""simple docstring"""
# This inner function sort imports between [ ].
def _replace(_A : Optional[Any] ):
lowerCamelCase_ =match.groups()[0]
if "," not in imports:
return f'[{imports}]'
lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
lowerCamelCase_ =keys[:-1]
return "[" + ", ".join([f'"{k}"' for k in sort_objects(_A )] ) + "]"
lowerCamelCase_ =import_statement.split("""\n""" )
if len(_A ) > 3:
# Here we have to sort internal imports that are on several lines (one per name):
# key: [
# "object1",
# "object2",
# ...
# ]
# We may have to ignore one or two lines on each side.
lowerCamelCase_ =2 if lines[1].strip() == """[""" else 1
lowerCamelCase_ =[(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )]
lowerCamelCase_ =sort_objects(_A , key=lambda _A : x[1] )
lowerCamelCase_ =[lines[x[0] + idx] for x in sorted_indices]
return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] )
elif len(_A ) == 3:
# Here we have to sort internal imports that are on one separate line:
# key: [
# "object1", "object2", ...
# ]
if _re_bracket_content.search(lines[1] ) is not None:
lowerCamelCase_ =_re_bracket_content.sub(_replace , lines[1] )
else:
lowerCamelCase_ =[part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
lowerCamelCase_ =keys[:-1]
lowerCamelCase_ =get_indent(lines[1] ) + """, """.join([f'"{k}"' for k in sort_objects(_A )] )
return "\n".join(_A )
else:
# Finally we have to deal with imports fitting on one line
lowerCamelCase_ =_re_bracket_content.sub(_replace , _A )
return import_statement
def __UpperCamelCase ( _A : List[Any] , _A : Optional[Any]=True ) ->str:
"""simple docstring"""
with open(_A , """r""" ) as f:
lowerCamelCase_ =f.read()
if "_import_structure" not in code:
return
# Blocks of indent level 0
lowerCamelCase_ =split_code_in_indented_blocks(
_A , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" )
# We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt).
for block_idx in range(1 , len(_A ) - 1 ):
# Check if the block contains some `_import_structure`s thingy to sort.
lowerCamelCase_ =main_blocks[block_idx]
lowerCamelCase_ =block.split("""\n""" )
# Get to the start of the imports.
lowerCamelCase_ =0
while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]:
# Skip dummy import blocks
if "import dummy" in block_lines[line_idx]:
lowerCamelCase_ =len(_A )
else:
line_idx += 1
if line_idx >= len(_A ):
continue
# Ignore beginning and last line: they don't contain anything.
lowerCamelCase_ ="""\n""".join(block_lines[line_idx:-1] )
lowerCamelCase_ =get_indent(block_lines[1] )
# Slit the internal block into blocks of indent level 1.
lowerCamelCase_ =split_code_in_indented_blocks(_A , indent_level=_A )
# We have two categories of import key: list or _import_structure[key].append/extend
lowerCamelCase_ =_re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key
# Grab the keys, but there is a trap: some lines are empty or just comments.
lowerCamelCase_ =[(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks]
# We only sort the lines with a key.
lowerCamelCase_ =[(i, key) for i, key in enumerate(_A ) if key is not None]
lowerCamelCase_ =[x[0] for x in sorted(_A , key=lambda _A : x[1] )]
# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.
lowerCamelCase_ =0
lowerCamelCase_ =[]
for i in range(len(_A ) ):
if keys[i] is None:
reordered_blocks.append(internal_blocks[i] )
else:
lowerCamelCase_ =sort_objects_in_import(internal_blocks[sorted_indices[count]] )
reordered_blocks.append(_A )
count += 1
# And we put our main block back together with its first and last line.
lowerCamelCase_ ="""\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] )
if code != "\n".join(_A ):
if check_only:
return True
else:
print(f'Overwriting {file}.' )
with open(_A , """w""" ) as f:
f.write("""\n""".join(_A ) )
def __UpperCamelCase ( _A : str=True ) ->List[Any]:
"""simple docstring"""
lowerCamelCase_ =[]
for root, _, files in os.walk(_A ):
if "__init__.py" in files:
lowerCamelCase_ =sort_imports(os.path.join(_A , """__init__.py""" ) , check_only=_A )
if result:
lowerCamelCase_ =[os.path.join(_A , """__init__.py""" )]
if len(_A ) > 0:
raise ValueError(f'Would overwrite {len(_A )} files, run `make style`.' )
if __name__ == "__main__":
__A : Tuple = argparse.ArgumentParser()
parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.')
__A : Optional[Any] = parser.parse_args()
sort_imports_in_all_inits(check_only=args.check_only)
| 75 |
from collections import namedtuple
import requests
from lxml import html # type: ignore
__A : Dict = namedtuple('covid_data', 'cases deaths recovered')
def __UpperCamelCase ( _A : str = "https://www.worldometers.info/coronavirus/" ) ->covid_data:
"""simple docstring"""
lowerCamelCase_ ="""//div[@class = \"maincounter-number\"]/span/text()"""
return covid_data(*html.fromstring(requests.get(_A ).content ).xpath(_A ) )
__A : Union[str, Any] = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}'
print(fmt.format(*covid_stats()))
| 75 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : List[Any] = logging.get_logger(__name__)
a : List[str] = {
"sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json",
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class a ( lowercase__ ):
"""simple docstring"""
a : Tuple = 'vit_msn'
def __init__( self : Any , __lowercase : Any=768 , __lowercase : Union[str, Any]=12 , __lowercase : Any=12 , __lowercase : int=3072 , __lowercase : Optional[Any]="gelu" , __lowercase : Optional[int]=0.0 , __lowercase : Union[str, Any]=0.0 , __lowercase : Union[str, Any]=0.02 , __lowercase : Tuple=1e-0_6 , __lowercase : Dict=224 , __lowercase : List[str]=16 , __lowercase : List[str]=3 , __lowercase : Dict=True , **__lowercase : Tuple , ) -> Dict:
super().__init__(**__lowercase )
__UpperCAmelCase : Optional[Any] = hidden_size
__UpperCAmelCase : str = num_hidden_layers
__UpperCAmelCase : List[Any] = num_attention_heads
__UpperCAmelCase : Union[str, Any] = intermediate_size
__UpperCAmelCase : Union[str, Any] = hidden_act
__UpperCAmelCase : str = hidden_dropout_prob
__UpperCAmelCase : Tuple = attention_probs_dropout_prob
__UpperCAmelCase : Optional[Any] = initializer_range
__UpperCAmelCase : List[Any] = layer_norm_eps
__UpperCAmelCase : List[Any] = image_size
__UpperCAmelCase : Optional[int] = patch_size
__UpperCAmelCase : Optional[Any] = num_channels
__UpperCAmelCase : Optional[int] = qkv_bias
| 63 |
import argparse
import torch
from datasets import load_dataset
from donut import DonutModel
from transformers import (
DonutImageProcessor,
DonutProcessor,
DonutSwinConfig,
DonutSwinModel,
MBartConfig,
MBartForCausalLM,
VisionEncoderDecoderModel,
XLMRobertaTokenizerFast,
)
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ):
SCREAMING_SNAKE_CASE__ = model.config
SCREAMING_SNAKE_CASE__ = DonutSwinConfig(
image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , )
SCREAMING_SNAKE_CASE__ = MBartConfig(
is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len(
model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , )
return encoder_config, decoder_config
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ):
if "encoder.model" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" )
if "decoder.model" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" )
if "patch_embed.proj" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" )
if "patch_embed.norm" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" )
if name.startswith("""encoder""" ):
if "layers" in name:
SCREAMING_SNAKE_CASE__ = """encoder.""" + name
if "attn.proj" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" )
if "attn" in name and "mask" not in name:
SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" )
if "norm1" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" )
if "norm2" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" )
if "mlp.fc1" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" )
if "mlp.fc2" in name:
SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" )
if name == "encoder.norm.weight":
SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight"""
if name == "encoder.norm.bias":
SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias"""
return name
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ):
for key in orig_state_dict.copy().keys():
SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ )
if "qkv" in key:
SCREAMING_SNAKE_CASE__ = key.split(""".""" )
SCREAMING_SNAKE_CASE__ = int(key_split[3] )
SCREAMING_SNAKE_CASE__ = int(key_split[5] )
SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
SCREAMING_SNAKE_CASE__ = val[:dim, :]
SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :]
SCREAMING_SNAKE_CASE__ = val[-dim:, :]
else:
SCREAMING_SNAKE_CASE__ = val[:dim]
SCREAMING_SNAKE_CASE__ = val[dim : dim * 2]
SCREAMING_SNAKE_CASE__ = val[-dim:]
elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
# HuggingFace implementation doesn't use attn_mask buffer
# and model doesn't use final LayerNorms for the encoder
pass
else:
SCREAMING_SNAKE_CASE__ = val
return orig_state_dict
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ):
# load original model
SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval()
# load HuggingFace model
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ )
model.eval()
SCREAMING_SNAKE_CASE__ = original_model.state_dict()
SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ )
model.load_state_dict(UpperCamelCase__ )
# verify results on scanned document
SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" )
SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" )
SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = DonutImageProcessor(
do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] )
SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values
if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>"""
SCREAMING_SNAKE_CASE__ = """When is the coffee break?"""
SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ )
elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>"""
elif model_name in [
"naver-clova-ix/donut-base-finetuned-cord-v1",
"naver-clova-ix/donut-base-finetuned-cord-v1-2560",
]:
SCREAMING_SNAKE_CASE__ = """<s_cord>"""
elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
SCREAMING_SNAKE_CASE__ = """s_cord-v2>"""
elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>"""
elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
# use a random prompt
SCREAMING_SNAKE_CASE__ = """hello world"""
else:
raise ValueError("""Model name not supported""" )
SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[
"""input_ids"""
]
SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ )
assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 )
# verify encoder hidden states
SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state
assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 )
# verify decoder hidden states
SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits
SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits
assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 )
print("""Looks ok!""" )
if pytorch_dump_folder_path is not None:
print(f'''Saving model and processor to {pytorch_dump_folder_path}''' )
model.save_pretrained(UpperCamelCase__ )
processor.save_pretrained(UpperCamelCase__ )
if push_to_hub:
model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" )
processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" )
if __name__ == "__main__":
_lowerCamelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='naver-clova-ix/donut-base-finetuned-docvqa',
required=False,
type=str,
help='Name of the original model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
required=False,
type=str,
help='Path to the output PyTorch model directory.',
)
parser.add_argument(
'--push_to_hub',
action='store_true',
help='Whether or not to push the converted model and processor to the 🤗 hub.',
)
_lowerCamelCase = parser.parse_args()
convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub) | 6 | 0 |
from math import pow, sqrt
def _lowerCAmelCase ( *__magic_name__ :float ):
UpperCAmelCase_ = len(__magic_name__ ) > 0 and all(value > 0.0 for value in values )
return result
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float ):
return (
round(sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__magic_name__ , __magic_name__ )
else ValueError('''Input Error: Molar mass values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float ):
return (
round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 )
if validate(__magic_name__ , __magic_name__ , __magic_name__ )
else ValueError(
'''Input Error: Molar mass and effusion rate values must greater than 0.''' )
)
| 407 |
from functools import lru_cache
@lru_cache
def _lowerCAmelCase ( __magic_name__ :int ):
if num < 0:
raise ValueError('''Number should not be negative.''' )
return 1 if num in (0, 1) else num * factorial(num - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 407 | 1 |
import requests
from bsa import BeautifulSoup
def _A ( _lowercase , _lowercase ) -> str:
"""simple docstring"""
__UpperCamelCase = BeautifulSoup(requests.get(_lowercase , params=_lowercase ).content , 'html.parser' )
__UpperCamelCase = soup.find('div' , attrs={'class': 'gs_ri'} )
__UpperCamelCase = div.find('div' , attrs={'class': 'gs_fl'} ).find_all('a' )
return anchors[2].get_text()
if __name__ == "__main__":
__snake_case = {
'''title''': (
'''Precisely geometry controlled microsupercapacitors for ultrahigh areal '''
'''capacitance, volumetric capacitance, and energy density'''
),
'''journal''': '''Chem. Mater.''',
'''volume''': 3_0,
'''pages''': '''3979-3990''',
'''year''': 2_0_1_8,
'''hl''': '''en''',
}
print(get_citation('''https://scholar.google.com/scholar_lookup''', params=params))
| 1 |
'''simple docstring'''
print((lambda quine: quine % quine)('print((lambda quine: quine %% quine)(%r))')) | 334 | 0 |
import numpy as np
from transformers import Pipeline
def __UpperCAmelCase ( lowerCamelCase_ : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = np.max(lowerCamelCase_ , axis=-1 , keepdims=lowerCamelCase_ )
SCREAMING_SNAKE_CASE_ : Tuple = np.exp(outputs - maxes )
return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCamelCase_ )
class lowerCAmelCase_ ( lowerCamelCase_ ):
def snake_case ( self ,**snake_case__ ):
SCREAMING_SNAKE_CASE_ : Optional[int] = {}
if "second_text" in kwargs:
SCREAMING_SNAKE_CASE_ : int = kwargs['second_text']
return preprocess_kwargs, {}, {}
def snake_case ( self ,snake_case__ ,snake_case__=None ):
return self.tokenizer(snake_case__ ,text_pair=snake_case__ ,return_tensors=self.framework )
def snake_case ( self ,snake_case__ ):
return self.model(**snake_case__ )
def snake_case ( self ,snake_case__ ):
SCREAMING_SNAKE_CASE_ : Dict = model_outputs.logits[0].numpy()
SCREAMING_SNAKE_CASE_ : Dict = softmax(snake_case__ )
SCREAMING_SNAKE_CASE_ : Dict = np.argmax(snake_case__ )
SCREAMING_SNAKE_CASE_ : List[Any] = self.model.config.idalabel[best_class]
SCREAMING_SNAKE_CASE_ : List[str] = probabilities[best_class].item()
SCREAMING_SNAKE_CASE_ : Dict = logits.tolist()
return {"label": label, "score": score, "logits": logits}
| 685 |
from collections.abc import Callable
from math import pi, sqrt
from random import uniform
from statistics import mean
def __UpperCAmelCase ( lowerCamelCase_ : int ) -> Union[str, Any]:
"""simple docstring"""
def is_in_circle(lowerCamelCase_ : float , lowerCamelCase_ : float ) -> bool:
SCREAMING_SNAKE_CASE_ : Any = sqrt((x**2) + (y**2) )
# Our circle has a radius of 1, so a distance
# greater than 1 would land outside the circle.
return distance_from_centre <= 1
# The proportion of guesses that landed in the circle
SCREAMING_SNAKE_CASE_ : Optional[int] = mean(
int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) )
for _ in range(lowerCamelCase_ ) )
# The ratio of the area for circle to square is pi/4.
SCREAMING_SNAKE_CASE_ : Tuple = proportion * 4
print(F'The estimated value of pi is {pi_estimate}' )
print(F'The numpy value of pi is {pi}' )
print(F'The total error is {abs(pi - pi_estimate )}' )
def __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : Callable[[float], float] , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 1.0 , ) -> float:
"""simple docstring"""
return mean(
function_to_integrate(uniform(lowerCamelCase_ , lowerCamelCase_ ) ) for _ in range(lowerCamelCase_ ) ) * (max_value - min_value)
def __UpperCAmelCase ( lowerCamelCase_ : int , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 1.0 ) -> None:
"""simple docstring"""
def identity_function(lowerCamelCase_ : float ) -> float:
return x
SCREAMING_SNAKE_CASE_ : str = area_under_curve_estimator(
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = (max_value * max_value - min_value * min_value) / 2
print('******************' )
print(F'Estimating area under y=x where x varies from {min_value} to {max_value}' )
print(F'Estimated value is {estimated_value}' )
print(F'Expected value is {expected_value}' )
print(F'Total error is {abs(estimated_value - expected_value )}' )
print('******************' )
def __UpperCAmelCase ( lowerCamelCase_ : int ) -> None:
"""simple docstring"""
def function_to_integrate(lowerCamelCase_ : float ) -> float:
return sqrt(4.0 - x * x )
SCREAMING_SNAKE_CASE_ : Dict = area_under_curve_estimator(
lowerCamelCase_ , lowerCamelCase_ , 0.0 , 2.0 )
print('******************' )
print('Estimating pi using area_under_curve_estimator' )
print(F'Estimated value is {estimated_value}' )
print(F'Expected value is {pi}' )
print(F'Total error is {abs(estimated_value - pi )}' )
print('******************' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 685 | 1 |
"""simple docstring"""
_lowercase = {'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []}
_lowercase = ['''a''', '''b''', '''c''', '''d''', '''e''']
def _snake_case ( snake_case__ : Dict , snake_case__ : str , snake_case__ : Optional[Any] ):
A = start
# add current to visited
visited.append(snake_case__ )
A = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
A = topological_sort(snake_case__ , snake_case__ , snake_case__ )
# if all neighbors visited add current to sort
sort.append(snake_case__ )
# if all vertices haven't been visited select a new one to visit
if len(snake_case__ ) != len(snake_case__ ):
for vertice in vertices:
if vertice not in visited:
A = topological_sort(snake_case__ , snake_case__ , snake_case__ )
# return sort
return sort
if __name__ == "__main__":
_lowercase = topological_sort('''a''', [], [])
print(sort) | 91 |
from .glue import GlueDataset, GlueDataTrainingArguments
from .language_modeling import (
LineByLineTextDataset,
LineByLineWithRefDataset,
LineByLineWithSOPTextDataset,
TextDataset,
TextDatasetForNextSentencePrediction,
)
from .squad import SquadDataset, SquadDataTrainingArguments
| 477 | 0 |
'''simple docstring'''
import os
import tempfile
import unittest
from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
DistilBertModel,
)
class _snake_case (__SCREAMING_SNAKE_CASE):
def __init__( self ,_snake_case ,_snake_case=13 ,_snake_case=7 ,_snake_case=True ,_snake_case=True ,_snake_case=False ,_snake_case=True ,_snake_case=99 ,_snake_case=32 ,_snake_case=5 ,_snake_case=4 ,_snake_case=37 ,_snake_case="gelu" ,_snake_case=0.1 ,_snake_case=0.1 ,_snake_case=5_12 ,_snake_case=16 ,_snake_case=2 ,_snake_case=0.02 ,_snake_case=3 ,_snake_case=4 ,_snake_case=None ,):
UpperCAmelCase_ : Tuple = parent
UpperCAmelCase_ : Tuple = batch_size
UpperCAmelCase_ : List[Any] = seq_length
UpperCAmelCase_ : str = is_training
UpperCAmelCase_ : Any = use_input_mask
UpperCAmelCase_ : Tuple = use_token_type_ids
UpperCAmelCase_ : Tuple = use_labels
UpperCAmelCase_ : Optional[Any] = vocab_size
UpperCAmelCase_ : List[str] = hidden_size
UpperCAmelCase_ : Union[str, Any] = num_hidden_layers
UpperCAmelCase_ : Dict = num_attention_heads
UpperCAmelCase_ : Optional[Any] = intermediate_size
UpperCAmelCase_ : List[Any] = hidden_act
UpperCAmelCase_ : str = hidden_dropout_prob
UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob
UpperCAmelCase_ : Tuple = max_position_embeddings
UpperCAmelCase_ : Tuple = type_vocab_size
UpperCAmelCase_ : str = type_sequence_label_size
UpperCAmelCase_ : List[str] = initializer_range
UpperCAmelCase_ : Tuple = num_labels
UpperCAmelCase_ : Optional[Any] = num_choices
UpperCAmelCase_ : Tuple = scope
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Any = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
UpperCAmelCase_ : Any = None
if self.use_input_mask:
UpperCAmelCase_ : Dict = random_attention_mask([self.batch_size, self.seq_length] )
UpperCAmelCase_ : str = None
UpperCAmelCase_ : int = None
UpperCAmelCase_ : Optional[int] = None
if self.use_labels:
UpperCAmelCase_ : Dict = ids_tensor([self.batch_size] ,self.type_sequence_label_size )
UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels )
UpperCAmelCase_ : List[Any] = ids_tensor([self.batch_size] ,self.num_choices )
UpperCAmelCase_ : Union[str, Any] = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCamelCase__ ( self ):
return DistilBertConfig(
vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,)
def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ):
UpperCAmelCase_ : Dict = DistilBertModel(config=_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase_ : Dict = model(_snake_case ,_snake_case )
UpperCAmelCase_ : List[Any] = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) )
def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ):
UpperCAmelCase_ : Dict = DistilBertForMaskedLM(config=_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase_ : Optional[int] = model(_snake_case ,attention_mask=_snake_case ,labels=_snake_case )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) )
def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ):
UpperCAmelCase_ : Optional[Any] = DistilBertForQuestionAnswering(config=_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase_ : Optional[int] = model(
_snake_case ,attention_mask=_snake_case ,start_positions=_snake_case ,end_positions=_snake_case )
self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) )
def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ):
UpperCAmelCase_ : Union[str, Any] = self.num_labels
UpperCAmelCase_ : int = DistilBertForSequenceClassification(_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase_ : int = model(_snake_case ,attention_mask=_snake_case ,labels=_snake_case )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) )
def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ):
UpperCAmelCase_ : List[str] = self.num_labels
UpperCAmelCase_ : Union[str, Any] = DistilBertForTokenClassification(config=_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase_ : Any = model(_snake_case ,attention_mask=_snake_case ,labels=_snake_case )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) )
def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ):
UpperCAmelCase_ : Dict = self.num_choices
UpperCAmelCase_ : str = DistilBertForMultipleChoice(config=_snake_case )
model.to(_snake_case )
model.eval()
UpperCAmelCase_ : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
UpperCAmelCase_ : List[str] = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
UpperCAmelCase_ : str = model(
_snake_case ,attention_mask=_snake_case ,labels=_snake_case ,)
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) )
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : int = self.prepare_config_and_inputs()
((UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_)) : int = config_and_inputs
UpperCAmelCase_ : str = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
class _snake_case (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase):
__A : Tuple =(
(
DistilBertModel,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
)
if is_torch_available()
else None
)
__A : Optional[Any] =(
{
"feature-extraction": DistilBertModel,
"fill-mask": DistilBertForMaskedLM,
"question-answering": DistilBertForQuestionAnswering,
"text-classification": DistilBertForSequenceClassification,
"token-classification": DistilBertForTokenClassification,
"zero-shot": DistilBertForSequenceClassification,
}
if is_torch_available()
else {}
)
__A : List[str] =True
__A : Optional[Any] =True
__A : Dict =True
__A : List[Any] =True
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Optional[int] = DistilBertModelTester(self )
UpperCAmelCase_ : Optional[Any] = ConfigTester(self ,config_class=_snake_case ,dim=37 )
def UpperCamelCase__ ( self ):
self.config_tester.run_common_tests()
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_model(*_snake_case )
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_masked_lm(*_snake_case )
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_question_answering(*_snake_case )
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_sequence_classification(*_snake_case )
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_token_classification(*_snake_case )
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_distilbert_for_multiple_choice(*_snake_case )
@slow
def UpperCamelCase__ ( self ):
for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase_ : Optional[Any] = DistilBertModel.from_pretrained(_snake_case )
self.assertIsNotNone(_snake_case )
@slow
@require_torch_gpu
def UpperCamelCase__ ( self ):
UpperCAmelCase_ , UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# BertForMultipleChoice behaves incorrectly in JIT environments.
if model_class == DistilBertForMultipleChoice:
return
UpperCAmelCase_ : Dict = True
UpperCAmelCase_ : Union[str, Any] = model_class(config=_snake_case )
UpperCAmelCase_ : Dict = self._prepare_for_class(_snake_case ,_snake_case )
UpperCAmelCase_ : Optional[Any] = torch.jit.trace(
_snake_case ,(inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) )
with tempfile.TemporaryDirectory() as tmp:
torch.jit.save(_snake_case ,os.path.join(_snake_case ,"traced_model.pt" ) )
UpperCAmelCase_ : Optional[Any] = torch.jit.load(os.path.join(_snake_case ,"traced_model.pt" ) ,map_location=_snake_case )
loaded(inputs_dict["input_ids"].to(_snake_case ) ,inputs_dict["attention_mask"].to(_snake_case ) )
@require_torch
class _snake_case (unittest.TestCase):
@slow
def UpperCamelCase__ ( self ):
UpperCAmelCase_ : Union[str, Any] = DistilBertModel.from_pretrained("distilbert-base-uncased" )
UpperCAmelCase_ : Optional[int] = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] )
UpperCAmelCase_ : List[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
UpperCAmelCase_ : Any = model(_snake_case ,attention_mask=_snake_case )[0]
UpperCAmelCase_ : Optional[int] = torch.Size((1, 11, 7_68) )
self.assertEqual(output.shape ,_snake_case )
UpperCAmelCase_ : Any = torch.tensor(
[[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,_snake_case ,atol=1E-4 ) )
| 323 |
'''simple docstring'''
import csv
import tweepy
# Twitter API credentials
_lowerCamelCase = """"""
_lowerCamelCase = """"""
_lowerCamelCase = """"""
_lowerCamelCase = """"""
def a__ ( _SCREAMING_SNAKE_CASE : str ) -> None:
"""simple docstring"""
UpperCAmelCase_ : List[Any] = tweepy.OAuthHandler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
auth.set_access_token(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : List[str] = tweepy.API(_SCREAMING_SNAKE_CASE )
# initialize a list to hold all the tweepy Tweets
UpperCAmelCase_ : str = []
# make initial request for most recent tweets (200 is the maximum allowed count)
UpperCAmelCase_ : Dict = api.user_timeline(screen_name=_SCREAMING_SNAKE_CASE , count=2_00 )
# save most recent tweets
alltweets.extend(_SCREAMING_SNAKE_CASE )
# save the id of the oldest tweet less one
UpperCAmelCase_ : Any = alltweets[-1].id - 1
# keep grabbing tweets until there are no tweets left to grab
while len(_SCREAMING_SNAKE_CASE ) > 0:
print(F'''getting tweets before {oldest}''' )
# all subsequent requests use the max_id param to prevent duplicates
UpperCAmelCase_ : Tuple = api.user_timeline(
screen_name=_SCREAMING_SNAKE_CASE , count=2_00 , max_id=_SCREAMING_SNAKE_CASE )
# save most recent tweets
alltweets.extend(_SCREAMING_SNAKE_CASE )
# update the id of the oldest tweet less one
UpperCAmelCase_ : Optional[int] = alltweets[-1].id - 1
print(F'''...{len(_SCREAMING_SNAKE_CASE )} tweets downloaded so far''' )
# transform the tweepy tweets into a 2D array that will populate the csv
UpperCAmelCase_ : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets]
# write the csv
with open(F'''new_{screen_name}_tweets.csv''' , "w" ) as f:
UpperCAmelCase_ : str = csv.writer(_SCREAMING_SNAKE_CASE )
writer.writerow(["id", "created_at", "text"] )
writer.writerows(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
# pass in the username of the account you want to download
get_all_tweets("""FirePing32""")
| 323 | 1 |
'''simple docstring'''
class __magic_name__ :
def __init__( self , snake_case_ , snake_case_ ):
lowercase =name
lowercase =val
def __str__( self ):
return f'{self.__class__.__name__}({self.name}, {self.val})'
def __lt__( self , snake_case_ ):
return self.val < other.val
class __magic_name__ :
def __init__( self , snake_case_ ):
lowercase ={}
lowercase ={}
lowercase =self.build_heap(snake_case_ )
def __getitem__( self , snake_case_ ):
return self.get_value(snake_case_ )
def _A( self , snake_case_ ):
return (idx - 1) // 2
def _A( self , snake_case_ ):
return idx * 2 + 1
def _A( self , snake_case_ ):
return idx * 2 + 2
def _A( self , snake_case_ ):
return self.heap_dict[key]
def _A( self , snake_case_ ):
lowercase =len(snake_case_ ) - 1
lowercase =self.get_parent_idx(snake_case_ )
for idx, i in enumerate(snake_case_ ):
lowercase =idx
lowercase =i.val
for i in range(snake_case_ , -1 , -1 ):
self.sift_down(snake_case_ , snake_case_ )
return array
def _A( self , snake_case_ , snake_case_ ):
while True:
lowercase =self.get_left_child_idx(snake_case_ ) # noqa: E741
lowercase =self.get_right_child_idx(snake_case_ )
lowercase =idx
if l < len(snake_case_ ) and array[l] < array[idx]:
lowercase =l
if r < len(snake_case_ ) and array[r] < array[smallest]:
lowercase =r
if smallest != idx:
lowercase , lowercase =array[smallest], array[idx]
(
(
lowercase
) , (
lowercase
) ,
) =(
self.idx_of_element[array[smallest]],
self.idx_of_element[array[idx]],
)
lowercase =smallest
else:
break
def _A( self , snake_case_ ):
lowercase =self.get_parent_idx(snake_case_ )
while p >= 0 and self.heap[p] > self.heap[idx]:
lowercase , lowercase =self.heap[idx], self.heap[p]
lowercase , lowercase =(
self.idx_of_element[self.heap[idx]],
self.idx_of_element[self.heap[p]],
)
lowercase =p
lowercase =self.get_parent_idx(snake_case_ )
def _A( self ):
return self.heap[0]
def _A( self ):
lowercase , lowercase =self.heap[-1], self.heap[0]
lowercase , lowercase =(
self.idx_of_element[self.heap[-1]],
self.idx_of_element[self.heap[0]],
)
lowercase =self.heap.pop()
del self.idx_of_element[x]
self.sift_down(0 , self.heap )
return x
def _A( self , snake_case_ ):
self.heap.append(snake_case_ )
lowercase =len(self.heap ) - 1
lowercase =node.val
self.sift_up(len(self.heap ) - 1 )
def _A( self ):
return len(self.heap ) == 0
def _A( self , snake_case_ , snake_case_ ):
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
lowercase =new_value
lowercase =new_value
self.sift_up(self.idx_of_element[node] )
_UpperCAmelCase : Any = Node('''R''', -1)
_UpperCAmelCase : Optional[int] = Node('''B''', 6)
_UpperCAmelCase : Tuple = Node('''A''', 3)
_UpperCAmelCase : Union[str, Any] = Node('''X''', 1)
_UpperCAmelCase : List[str] = Node('''E''', 4)
# Use one of these two ways to generate Min-Heap
# Generating Min-Heap from array
_UpperCAmelCase : Union[str, Any] = MinHeap([r, b, a, x, e])
# Generating Min-Heap by Insert method
# myMinHeap.insert(a)
# myMinHeap.insert(b)
# myMinHeap.insert(x)
# myMinHeap.insert(r)
# myMinHeap.insert(e)
# Before
print('''Min Heap - before decrease key''')
for i in my_min_heap.heap:
print(i)
print('''Min Heap - After decrease key of node [B -> -17]''')
my_min_heap.decrease_key(b, -17)
# After
for i in my_min_heap.heap:
print(i)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 72 |
"""simple docstring"""
from decimal import Decimal, getcontext
from math import ceil, factorial
def __lowerCAmelCase ( __UpperCamelCase : int ):
'''simple docstring'''
if not isinstance(__UpperCamelCase , __UpperCamelCase ):
raise TypeError("""Undefined for non-integers""" )
elif precision < 1:
raise ValueError("""Undefined for non-natural numbers""" )
snake_case_ : str = precision
snake_case_ : Any = ceil(precision / 1_4 )
snake_case_ : Dict = 4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt()
snake_case_ : Optional[Any] = 1
snake_case_ : List[str] = 1_3_5_9_1_4_0_9
snake_case_ : Optional[int] = Decimal(__UpperCamelCase )
for k in range(1 , __UpperCamelCase ):
snake_case_ : Any = factorial(6 * k ) // (factorial(3 * k ) * factorial(__UpperCamelCase ) ** 3)
linear_term += 5_4_5_1_4_0_1_3_4
exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0
partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term
return str(constant_term / partial_sum )[:-1]
if __name__ == "__main__":
__lowerCAmelCase : int = 50
print(F'''The first {n} digits of pi is: {pi(n)}''')
| 58 | 0 |
'''simple docstring'''
class A_ :
'''simple docstring'''
def __init__( self , _A) -> Any:
"""simple docstring"""
_UpperCAmelCase : List[str] = arr.split(''',''')
def snake_case__ ( self) -> Optional[Any]:
"""simple docstring"""
_UpperCAmelCase : Dict = [int(self.array[0])] * len(self.array)
_UpperCAmelCase : Union[str, Any] = [int(self.array[0])] * len(self.array)
for i in range(1 , len(self.array)):
_UpperCAmelCase : List[Any] = max(
int(self.array[i]) + sum_value[i - 1] , int(self.array[i]))
_UpperCAmelCase : Tuple = max(sum_value[i] , rear[i - 1])
return rear[len(self.array) - 1]
if __name__ == "__main__":
SCREAMING_SNAKE_CASE = input('please input some numbers:')
SCREAMING_SNAKE_CASE = SubArray(whole_array)
SCREAMING_SNAKE_CASE = array.solve_sub_array()
print(('the results is:', re))
| 721 |
import re
import time
from typing import Optional
import IPython.display as disp
from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def _lowerCamelCase ( __A : List[str] ) -> Union[str, Any]:
_UpperCAmelCase : Dict = int(__A )
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : List[str] = t // 3_600, (t // 60) % 60, t % 60
return f'''{h}:{m:02d}:{s:02d}''' if h != 0 else f'''{m:02d}:{s:02d}'''
def _lowerCamelCase ( __A : List[str] , __A : List[Any] , __A : str , __A : int , __A : Dict=300 ) -> int:
# docstyle-ignore
return f'''
<div>
{prefix}
<progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
{label}
</div>
'''
def _lowerCamelCase ( __A : List[str] ) -> Optional[int]:
_UpperCAmelCase : Optional[Any] = '''<table border="1" class="dataframe">\n'''
html_code += """ <thead>\n <tr style="text-align: left;">\n"""
for i in items[0]:
html_code += f''' <th>{i}</th>\n'''
html_code += " </tr>\n </thead>\n <tbody>\n"
for line in items[1:]:
html_code += " <tr>\n"
for elt in line:
_UpperCAmelCase : Tuple = f'''{elt:.6f}''' if isinstance(__A , __A ) else str(__A )
html_code += f''' <td>{elt}</td>\n'''
html_code += " </tr>\n"
html_code += " </tbody>\n</table><p>"
return html_code
class A_ :
'''simple docstring'''
_SCREAMING_SNAKE_CASE : Optional[Any] = 5
_SCREAMING_SNAKE_CASE : Optional[Any] = 0.2
def __init__( self , _A , _A = None , _A = True , _A = None , _A = 300 , ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase : List[str] = total
_UpperCAmelCase : Optional[int] = '''''' if prefix is None else prefix
_UpperCAmelCase : Any = leave
_UpperCAmelCase : List[Any] = parent
_UpperCAmelCase : Optional[int] = width
_UpperCAmelCase : Optional[int] = None
_UpperCAmelCase : str = None
_UpperCAmelCase : int = None
def snake_case__ ( self , _A , _A = False , _A = None) -> Optional[Any]:
"""simple docstring"""
_UpperCAmelCase : List[str] = value
if comment is not None:
_UpperCAmelCase : str = comment
if self.last_value is None:
_UpperCAmelCase : Tuple = time.time()
_UpperCAmelCase : Optional[Any] = value
_UpperCAmelCase : Tuple = None
_UpperCAmelCase : List[str] = self.warmup
_UpperCAmelCase : Optional[Any] = 1
self.update_bar(_A)
elif value <= self.last_value and not force_update:
return
elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for , self.total):
if self.first_calls > 0:
self.first_calls -= 1
_UpperCAmelCase : Union[str, Any] = time.time()
_UpperCAmelCase : int = current_time - self.start_time
# We could have value = self.start_value if the update is called twixe with the same start value.
if value > self.start_value:
_UpperCAmelCase : str = self.elapsed_time / (value - self.start_value)
else:
_UpperCAmelCase : List[str] = None
if value >= self.total:
_UpperCAmelCase : str = self.total
_UpperCAmelCase : Optional[Any] = None
if not self.leave:
self.close()
elif self.average_time_per_item is not None:
_UpperCAmelCase : List[str] = self.average_time_per_item * (self.total - value)
self.update_bar(_A)
_UpperCAmelCase : str = value
_UpperCAmelCase : List[Any] = current_time
if self.average_time_per_item is None:
_UpperCAmelCase : str = 1
else:
_UpperCAmelCase : Optional[Any] = max(int(self.update_every / self.average_time_per_item) , 1)
def snake_case__ ( self , _A , _A=None) -> List[Any]:
"""simple docstring"""
_UpperCAmelCase : Union[str, Any] = ''' ''' * (len(str(self.total)) - len(str(_A))) + str(_A)
if self.elapsed_time is None:
_UpperCAmelCase : List[Any] = f'''[{spaced_value}/{self.total} : < :'''
elif self.predicted_remaining is None:
_UpperCAmelCase : Any = f'''[{spaced_value}/{self.total} {format_time(self.elapsed_time)}'''
else:
_UpperCAmelCase : int = (
f'''[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <'''
f''' {format_time(self.predicted_remaining)}'''
)
self.label += f''', {1/self.average_time_per_item:.2f} it/s'''
self.label += "]" if self.comment is None or len(self.comment) == 0 else f''', {self.comment}]'''
self.display()
def snake_case__ ( self) -> List[Any]:
"""simple docstring"""
_UpperCAmelCase : Tuple = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width)
if self.parent is not None:
# If this is a child bar, the parent will take care of the display.
self.parent.display()
return
if self.output is None:
_UpperCAmelCase : Tuple = disp.display(disp.HTML(self.html_code) , display_id=_A)
else:
self.output.update(disp.HTML(self.html_code))
def snake_case__ ( self) -> int:
"""simple docstring"""
if self.parent is None and self.output is not None:
self.output.update(disp.HTML(''''''))
class A_ ( __lowercase ):
'''simple docstring'''
def __init__( self , _A , _A=None) -> Optional[Any]:
"""simple docstring"""
super().__init__(_A)
_UpperCAmelCase : List[str] = None if column_names is None else [column_names]
_UpperCAmelCase : Any = None
def snake_case__ ( self) -> List[str]:
"""simple docstring"""
_UpperCAmelCase : Optional[int] = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width)
if self.inner_table is not None:
self.html_code += text_to_html_table(self.inner_table)
if self.child_bar is not None:
self.html_code += self.child_bar.html_code
if self.output is None:
_UpperCAmelCase : Optional[int] = disp.display(disp.HTML(self.html_code) , display_id=_A)
else:
self.output.update(disp.HTML(self.html_code))
def snake_case__ ( self , _A) -> str:
"""simple docstring"""
if self.inner_table is None:
_UpperCAmelCase : Union[str, Any] = [list(values.keys()), list(values.values())]
else:
_UpperCAmelCase : Tuple = self.inner_table[0]
if len(self.inner_table) == 1:
# We give a chance to update the column names at the first iteration
for key in values.keys():
if key not in columns:
columns.append(_A)
_UpperCAmelCase : str = columns
self.inner_table.append([values[c] for c in columns])
def snake_case__ ( self , _A , _A=None , _A=300) -> int:
"""simple docstring"""
_UpperCAmelCase : Optional[int] = NotebookProgressBar(_A , prefix=_A , parent=self , width=_A)
return self.child_bar
def snake_case__ ( self) -> Union[str, Any]:
"""simple docstring"""
_UpperCAmelCase : Optional[Any] = None
self.display()
class A_ ( __lowercase ):
'''simple docstring'''
def __init__( self) -> Union[str, Any]:
"""simple docstring"""
_UpperCAmelCase : List[Any] = None
_UpperCAmelCase : int = None
_UpperCAmelCase : List[Any] = False
def snake_case__ ( self , _A , _A , _A , **_A) -> int:
"""simple docstring"""
_UpperCAmelCase : Union[str, Any] = '''Epoch''' if args.evaluation_strategy == IntervalStrategy.EPOCH else '''Step'''
_UpperCAmelCase : List[str] = 0
_UpperCAmelCase : List[Any] = 0
_UpperCAmelCase : List[Any] = [self.first_column] + ['''Training Loss''']
if args.evaluation_strategy != IntervalStrategy.NO:
column_names.append('''Validation Loss''')
_UpperCAmelCase : int = NotebookTrainingTracker(state.max_steps , _A)
def snake_case__ ( self , _A , _A , _A , **_A) -> Any:
"""simple docstring"""
_UpperCAmelCase : Tuple = int(state.epoch) if int(state.epoch) == state.epoch else f'''{state.epoch:.2f}'''
self.training_tracker.update(
state.global_step + 1 , comment=f'''Epoch {epoch}/{state.num_train_epochs}''' , force_update=self._force_next_update , )
_UpperCAmelCase : List[str] = False
def snake_case__ ( self , _A , _A , _A , _A=None , **_A) -> List[str]:
"""simple docstring"""
if not has_length(_A):
return
if self.prediction_bar is None:
if self.training_tracker is not None:
_UpperCAmelCase : Union[str, Any] = self.training_tracker.add_child(len(_A))
else:
_UpperCAmelCase : Dict = NotebookProgressBar(len(_A))
self.prediction_bar.update(1)
else:
self.prediction_bar.update(self.prediction_bar.value + 1)
def snake_case__ ( self , _A , _A , _A , **_A) -> str:
"""simple docstring"""
if self.prediction_bar is not None:
self.prediction_bar.close()
_UpperCAmelCase : List[Any] = None
def snake_case__ ( self , _A , _A , _A , _A=None , **_A) -> List[Any]:
"""simple docstring"""
if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
_UpperCAmelCase : Any = {'''Training Loss''': logs['''loss''']}
# First column is necessarily Step sine we're not in epoch eval strategy
_UpperCAmelCase : Union[str, Any] = state.global_step
self.training_tracker.write_line(_A)
def snake_case__ ( self , _A , _A , _A , _A=None , **_A) -> Dict:
"""simple docstring"""
if self.training_tracker is not None:
_UpperCAmelCase : List[str] = {'''Training Loss''': '''No log''', '''Validation Loss''': '''No log'''}
for log in reversed(state.log_history):
if "loss" in log:
_UpperCAmelCase : Any = log['''loss''']
break
if self.first_column == "Epoch":
_UpperCAmelCase : Optional[int] = int(state.epoch)
else:
_UpperCAmelCase : Union[str, Any] = state.global_step
_UpperCAmelCase : List[str] = '''eval'''
for k in metrics:
if k.endswith('''_loss'''):
_UpperCAmelCase : str = re.sub(R'''\_loss$''' , '''''' , _A)
_UpperCAmelCase : Optional[Any] = metrics.pop('''total_flos''' , _A)
_UpperCAmelCase : Optional[int] = metrics.pop('''epoch''' , _A)
_UpperCAmelCase : Union[str, Any] = metrics.pop(f'''{metric_key_prefix}_runtime''' , _A)
_UpperCAmelCase : List[Any] = metrics.pop(f'''{metric_key_prefix}_samples_per_second''' , _A)
_UpperCAmelCase : Optional[Any] = metrics.pop(f'''{metric_key_prefix}_steps_per_second''' , _A)
_UpperCAmelCase : List[str] = metrics.pop(f'''{metric_key_prefix}_jit_compilation_time''' , _A)
for k, v in metrics.items():
if k == f'''{metric_key_prefix}_loss''':
_UpperCAmelCase : Optional[int] = v
else:
_UpperCAmelCase : Union[str, Any] = k.split('''_''')
_UpperCAmelCase : List[str] = ''' '''.join([part.capitalize() for part in splits[1:]])
_UpperCAmelCase : List[str] = v
self.training_tracker.write_line(_A)
self.training_tracker.remove_child()
_UpperCAmelCase : List[str] = None
# Evaluation takes a long time so we should force the next update.
_UpperCAmelCase : List[Any] = True
def snake_case__ ( self , _A , _A , _A , **_A) -> List[str]:
"""simple docstring"""
self.training_tracker.update(
state.global_step , comment=f'''Epoch {int(state.epoch)}/{state.num_train_epochs}''' , force_update=_A)
_UpperCAmelCase : Optional[Any] = None
| 186 | 0 |
"""simple docstring"""
from __future__ import annotations
from itertools import permutations
from random import randint
from timeit import repeat
def a__ ( ) -> tuple[list[int], int]:
lowerCamelCase = [randint(-10_00 , 10_00 ) for i in range(10 )]
lowerCamelCase = randint(-50_00 , 50_00 )
return (arr, r)
lowerCAmelCase : List[str] = make_dataset()
def a__ ( snake_case__ , snake_case__ ) -> tuple[int, ...]:
for triplet in permutations(lowercase_ , 3 ):
if sum(lowercase_ ) == target:
return tuple(sorted(lowercase_ ) )
return (0, 0, 0)
def a__ ( snake_case__ , snake_case__ ) -> tuple[int, int, int]:
arr.sort()
lowerCamelCase = len(lowercase_ )
for i in range(n - 1 ):
lowerCamelCase , lowerCamelCase = i + 1, n - 1
while left < right:
if arr[i] + arr[left] + arr[right] == target:
return (arr[i], arr[left], arr[right])
elif arr[i] + arr[left] + arr[right] < target:
left += 1
elif arr[i] + arr[left] + arr[right] > target:
right -= 1
return (0, 0, 0)
def a__ ( ) -> tuple[float, float]:
lowerCamelCase = """
from __main__ import dataset, triplet_sum1, triplet_sum2
"""
lowerCamelCase = """
triplet_sum1(*dataset)
"""
lowerCamelCase = """
triplet_sum2(*dataset)
"""
lowerCamelCase = repeat(setup=lowercase_ , stmt=lowercase_ , repeat=5 , number=1_00_00 )
lowerCamelCase = repeat(setup=lowercase_ , stmt=lowercase_ , repeat=5 , number=1_00_00 )
return (min(lowercase_ ), min(lowercase_ ))
if __name__ == "__main__":
from doctest import testmod
testmod()
lowerCAmelCase : Dict = solution_times()
print(F"""The time for naive implementation is {times[0]}.""")
print(F"""The time for optimized implementation is {times[1]}.""")
| 543 |
"""simple docstring"""
import re
import string
from collections import Counter
import sacrebleu
import sacremoses
from packaging import version
import datasets
__SCREAMING_SNAKE_CASE : Optional[int] = '''
@inproceedings{xu-etal-2016-optimizing,
title = {Optimizing Statistical Machine Translation for Text Simplification},
authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},
journal = {Transactions of the Association for Computational Linguistics},
volume = {4},
year={2016},
url = {https://www.aclweb.org/anthology/Q16-1029},
pages = {401--415
},
@inproceedings{post-2018-call,
title = "A Call for Clarity in Reporting {BLEU} Scores",
author = "Post, Matt",
booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
month = oct,
year = "2018",
address = "Belgium, Brussels",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/W18-6319",
pages = "186--191",
}
'''
__SCREAMING_SNAKE_CASE : List[str] = '''\
WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU
It can be used to evaluate the quality of machine-generated texts.
'''
__SCREAMING_SNAKE_CASE : Optional[Any] = '''
Calculates sari score (between 0 and 100) given a list of source and predicted
sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.
Args:
sources: list of source sentences where each sentence should be a string.
predictions: list of predicted sentences where each sentence should be a string.
references: list of lists of reference sentences where each sentence should be a string.
Returns:
sari: sari score
sacrebleu: sacrebleu score
exact: exact score
Examples:
>>> sources=["About 95 species are currently accepted ."]
>>> predictions=["About 95 you now get in ."]
>>> references=[["About 95 species are currently known ."]]
>>> wiki_split = datasets.load_metric("wiki_split")
>>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)
>>> print(results)
{\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}
'''
def lowerCAmelCase_( lowercase_ : Union[str, Any] ) -> str:
def remove_articles(lowercase_ : int ):
_lowerCamelCase = re.compile(r'''\b(a|an|the)\b''' , re.UNICODE )
return re.sub(lowercase_ , ''' ''' , lowercase_ )
def white_space_fix(lowercase_ : List[Any] ):
return " ".join(text.split() )
def remove_punc(lowercase_ : Dict ):
_lowerCamelCase = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowercase_ : Union[str, Any] ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )
def lowerCAmelCase_( lowercase_ : List[str] , lowercase_ : Optional[Any] ) -> Union[str, Any]:
return int(normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) )
def lowerCAmelCase_( lowercase_ : Any , lowercase_ : Tuple ) -> Tuple:
_lowerCamelCase = [any(compute_exact(lowercase_ , lowercase_ ) for ref in refs ) for pred, refs in zip(lowercase_ , lowercase_ )]
return (sum(lowercase_ ) / len(lowercase_ )) * 1_00
def lowerCAmelCase_( lowercase_ : Tuple , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : str ) -> Optional[int]:
_lowerCamelCase = [rgram for rgrams in rgramslist for rgram in rgrams]
_lowerCamelCase = Counter(lowercase_ )
_lowerCamelCase = Counter(lowercase_ )
_lowerCamelCase = Counter()
for sgram, scount in sgramcounter.items():
_lowerCamelCase = scount * numref
_lowerCamelCase = Counter(lowercase_ )
_lowerCamelCase = Counter()
for cgram, ccount in cgramcounter.items():
_lowerCamelCase = ccount * numref
# KEEP
_lowerCamelCase = sgramcounter_rep & cgramcounter_rep
_lowerCamelCase = keepgramcounter_rep & rgramcounter
_lowerCamelCase = sgramcounter_rep & rgramcounter
_lowerCamelCase = 0
_lowerCamelCase = 0
for keepgram in keepgramcountergood_rep:
keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
# Fix an alleged bug [2] in the keep score computation.
# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
keeptmpscorea += keepgramcountergood_rep[keepgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
_lowerCamelCase = 1
_lowerCamelCase = 1
if len(lowercase_ ) > 0:
_lowerCamelCase = keeptmpscorea / len(lowercase_ )
if len(lowercase_ ) > 0:
# Fix an alleged bug [2] in the keep score computation.
# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
_lowerCamelCase = keeptmpscorea / sum(keepgramcounterall_rep.values() )
_lowerCamelCase = 0
if keepscore_precision > 0 or keepscore_recall > 0:
_lowerCamelCase = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)
# DELETION
_lowerCamelCase = sgramcounter_rep - cgramcounter_rep
_lowerCamelCase = delgramcounter_rep - rgramcounter
_lowerCamelCase = sgramcounter_rep - rgramcounter
_lowerCamelCase = 0
_lowerCamelCase = 0
for delgram in delgramcountergood_rep:
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
_lowerCamelCase = 1
if len(lowercase_ ) > 0:
_lowerCamelCase = deltmpscorea / len(lowercase_ )
# ADDITION
_lowerCamelCase = set(lowercase_ ) - set(lowercase_ )
_lowerCamelCase = set(lowercase_ ) & set(lowercase_ )
_lowerCamelCase = set(lowercase_ ) - set(lowercase_ )
_lowerCamelCase = 0
for addgram in addgramcountergood:
addtmpscore += 1
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
_lowerCamelCase = 1
_lowerCamelCase = 1
if len(lowercase_ ) > 0:
_lowerCamelCase = addtmpscore / len(lowercase_ )
if len(lowercase_ ) > 0:
_lowerCamelCase = addtmpscore / len(lowercase_ )
_lowerCamelCase = 0
if addscore_precision > 0 or addscore_recall > 0:
_lowerCamelCase = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)
return (keepscore, delscore_precision, addscore)
def lowerCAmelCase_( lowercase_ : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : str ) -> List[str]:
_lowerCamelCase = len(lowercase_ )
_lowerCamelCase = ssent.split(''' ''' )
_lowerCamelCase = csent.split(''' ''' )
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
for rsent in rsents:
_lowerCamelCase = rsent.split(''' ''' )
_lowerCamelCase = []
_lowerCamelCase = []
_lowerCamelCase = []
ragramslist.append(lowercase_ )
for i in range(0 , len(lowercase_ ) - 1 ):
if i < len(lowercase_ ) - 1:
_lowerCamelCase = ragrams[i] + ''' ''' + ragrams[i + 1]
ragrams.append(lowercase_ )
if i < len(lowercase_ ) - 2:
_lowerCamelCase = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2]
ragrams.append(lowercase_ )
if i < len(lowercase_ ) - 3:
_lowerCamelCase = ragrams[i] + ''' ''' + ragrams[i + 1] + ''' ''' + ragrams[i + 2] + ''' ''' + ragrams[i + 3]
ragrams.append(lowercase_ )
ragramslist.append(lowercase_ )
ragramslist.append(lowercase_ )
ragramslist.append(lowercase_ )
for i in range(0 , len(lowercase_ ) - 1 ):
if i < len(lowercase_ ) - 1:
_lowerCamelCase = sagrams[i] + ''' ''' + sagrams[i + 1]
sagrams.append(lowercase_ )
if i < len(lowercase_ ) - 2:
_lowerCamelCase = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2]
sagrams.append(lowercase_ )
if i < len(lowercase_ ) - 3:
_lowerCamelCase = sagrams[i] + ''' ''' + sagrams[i + 1] + ''' ''' + sagrams[i + 2] + ''' ''' + sagrams[i + 3]
sagrams.append(lowercase_ )
for i in range(0 , len(lowercase_ ) - 1 ):
if i < len(lowercase_ ) - 1:
_lowerCamelCase = cagrams[i] + ''' ''' + cagrams[i + 1]
cagrams.append(lowercase_ )
if i < len(lowercase_ ) - 2:
_lowerCamelCase = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2]
cagrams.append(lowercase_ )
if i < len(lowercase_ ) - 3:
_lowerCamelCase = cagrams[i] + ''' ''' + cagrams[i + 1] + ''' ''' + cagrams[i + 2] + ''' ''' + cagrams[i + 3]
cagrams.append(lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) = SARIngram(lowercase_ , lowercase_ , lowercase_ , lowercase_ )
_lowerCamelCase = sum([keepascore, keepascore, keepascore, keepascore] ) / 4
_lowerCamelCase = sum([delascore, delascore, delascore, delascore] ) / 4
_lowerCamelCase = sum([addascore, addascore, addascore, addascore] ) / 4
_lowerCamelCase = (avgkeepscore + avgdelscore + avgaddscore) / 3
return finalscore
def lowerCAmelCase_( lowercase_ : List[str] , lowercase_ : bool = True , lowercase_ : str = "13a" , lowercase_ : bool = True ) -> int:
# Normalization is requried for the ASSET dataset (one of the primary
# datasets in sentence simplification) to allow using space
# to split the sentence. Even though Wiki-Auto and TURK datasets,
# do not require normalization, we do it for consistency.
# Code adapted from the EASSE library [1] written by the authors of the ASSET dataset.
# [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7
if lowercase:
_lowerCamelCase = sentence.lower()
if tokenizer in ["13a", "intl"]:
if version.parse(sacrebleu.__version__ ).major >= 2:
_lowerCamelCase = sacrebleu.metrics.bleu._get_tokenizer(lowercase_ )()(lowercase_ )
else:
_lowerCamelCase = sacrebleu.TOKENIZERS[tokenizer]()(lowercase_ )
elif tokenizer == "moses":
_lowerCamelCase = sacremoses.MosesTokenizer().tokenize(lowercase_ , return_str=lowercase_ , escape=lowercase_ )
elif tokenizer == "penn":
_lowerCamelCase = sacremoses.MosesTokenizer().penn_tokenize(lowercase_ , return_str=lowercase_ )
else:
_lowerCamelCase = sentence
if not return_str:
_lowerCamelCase = normalized_sent.split()
return normalized_sent
def lowerCAmelCase_( lowercase_ : Any , lowercase_ : Any , lowercase_ : List[Any] ) -> Optional[int]:
if not (len(lowercase_ ) == len(lowercase_ ) == len(lowercase_ )):
raise ValueError('''Sources length must match predictions and references lengths.''' )
_lowerCamelCase = 0
for src, pred, refs in zip(lowercase_ , lowercase_ , lowercase_ ):
sari_score += SARIsent(normalize(lowercase_ ) , normalize(lowercase_ ) , [normalize(lowercase_ ) for sent in refs] )
_lowerCamelCase = sari_score / len(lowercase_ )
return 1_00 * sari_score
def lowerCAmelCase_( lowercase_ : Any , lowercase_ : Any , lowercase_ : List[Any]="exp" , lowercase_ : List[Any]=None , lowercase_ : Optional[Any]=False , lowercase_ : List[Any]=False , lowercase_ : List[Any]=False , ) -> Dict:
_lowerCamelCase = len(references[0] )
if any(len(lowercase_ ) != references_per_prediction for refs in references ):
raise ValueError('''Sacrebleu requires the same number of references for each prediction''' )
_lowerCamelCase = [[refs[i] for refs in references] for i in range(lowercase_ )]
_lowerCamelCase = sacrebleu.corpus_bleu(
lowercase_ , lowercase_ , smooth_method=lowercase_ , smooth_value=lowercase_ , force=lowercase_ , lowercase=lowercase_ , use_effective_order=lowercase_ , )
return output.score
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION )
class lowerCamelCase_( datasets.Metric ):
'''simple docstring'''
def snake_case__ ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' , id='''sequence''' ),
'''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ),
} ) , codebase_urls=[
'''https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py''',
'''https://github.com/cocoxu/simplification/blob/master/SARI.py''',
'''https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py''',
'''https://github.com/mjpost/sacreBLEU''',
] , reference_urls=[
'''https://www.aclweb.org/anthology/Q16-1029.pdf''',
'''https://github.com/mjpost/sacreBLEU''',
'''https://en.wikipedia.org/wiki/BLEU''',
'''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''',
] , )
def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
_lowerCamelCase = {}
result.update({'''sari''': compute_sari(sources=lowerCamelCase__ , predictions=lowerCamelCase__ , references=lowerCamelCase__ )} )
result.update({'''sacrebleu''': compute_sacrebleu(predictions=lowerCamelCase__ , references=lowerCamelCase__ )} )
result.update({'''exact''': compute_em(predictions=lowerCamelCase__ , references=lowerCamelCase__ )} )
return result
| 661 | 0 |
'''simple docstring'''
import os
from typing import List, Optional, Union
from ...tokenization_utils import PreTrainedTokenizer
from ...tokenization_utils_base import AddedToken
from ...utils import logging
UpperCamelCase : str = logging.get_logger(__name__)
UpperCamelCase : int = {"""vocab_file""": """vocab.txt"""}
UpperCamelCase : Union[str, Any] = {
"""vocab_file""": {
"""facebook/esm2_t6_8M_UR50D""": """https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt""",
"""facebook/esm2_t12_35M_UR50D""": """https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt""",
},
}
UpperCamelCase : Optional[int] = {
"""facebook/esm2_t6_8M_UR50D""": 1_024,
"""facebook/esm2_t12_35M_UR50D""": 1_024,
}
def SCREAMING_SNAKE_CASE__ ( snake_case : str ) -> Optional[int]:
"""simple docstring"""
with open(snake_case , 'r' ) as f:
a : Optional[Any] = f.read().splitlines()
return [l.strip() for l in lines]
class UpperCamelCase ( a_ ):
"""simple docstring"""
A : Optional[Any] = VOCAB_FILES_NAMES
A : Dict = PRETRAINED_VOCAB_FILES_MAP
A : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A : Any = ["input_ids", "attention_mask"]
def __init__( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]="<unk>" , UpperCAmelCase_ : Union[str, Any]="<cls>" , UpperCAmelCase_ : str="<pad>" , UpperCAmelCase_ : Optional[int]="<mask>" , UpperCAmelCase_ : List[str]="<eos>" , **UpperCAmelCase_ : str , ):
"""simple docstring"""
super().__init__(**UpperCAmelCase_)
a : Optional[Any] = load_vocab_file(UpperCAmelCase_)
a : Tuple = dict(enumerate(self.all_tokens))
a : Dict = {tok: ind for ind, tok in enumerate(self.all_tokens)}
a : Any = unk_token
a : List[Any] = cls_token
a : List[str] = pad_token
a : Optional[int] = mask_token
a : Dict = eos_token
a : Optional[Any] = self.all_tokens
self._create_trie(self.unique_no_split_tokens)
def SCREAMING_SNAKE_CASE_ ( self : List[Any] , UpperCAmelCase_ : int):
"""simple docstring"""
return self._id_to_token.get(UpperCAmelCase_ , self.unk_token)
def SCREAMING_SNAKE_CASE_ ( self : str , UpperCAmelCase_ : str):
"""simple docstring"""
return self._token_to_id.get(UpperCAmelCase_ , self._token_to_id.get(self.unk_token))
def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int):
"""simple docstring"""
return text.split()
def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , UpperCAmelCase_ : int=False):
"""simple docstring"""
return len(self._id_to_token)
def SCREAMING_SNAKE_CASE_ ( self : str):
"""simple docstring"""
return {token: i for i, token in enumerate(self.all_tokens)}
def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , UpperCAmelCase_ : str):
"""simple docstring"""
return self._token_to_id.get(UpperCAmelCase_ , self._token_to_id.get(self.unk_token))
def SCREAMING_SNAKE_CASE_ ( self : Any , UpperCAmelCase_ : int):
"""simple docstring"""
return self._id_to_token.get(UpperCAmelCase_ , self.unk_token)
def SCREAMING_SNAKE_CASE_ ( self : int , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None):
"""simple docstring"""
a : List[Any] = [self.cls_token_id]
a : Optional[Any] = [self.eos_token_id] # No sep token in ESM vocabulary
if token_ids_a is None:
if self.eos_token_id is None:
return cls + token_ids_a
else:
return cls + token_ids_a + sep
elif self.eos_token_id is None:
raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!')
return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token
def SCREAMING_SNAKE_CASE_ ( self : List[str] , UpperCAmelCase_ : List , UpperCAmelCase_ : Optional[List] = None , UpperCAmelCase_ : bool = False):
"""simple docstring"""
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
'You should not supply a second sequence if the provided sequence of '
'ids is already formatted with special tokens for the model.')
return [1 if token in self.all_special_ids else 0 for token in token_ids_a]
a : int = [1] + ([0] * len(UpperCAmelCase_)) + [1]
if token_ids_a is not None:
mask += [0] * len(UpperCAmelCase_) + [1]
return mask
def SCREAMING_SNAKE_CASE_ ( self : Tuple , UpperCAmelCase_ : Any , UpperCAmelCase_ : int):
"""simple docstring"""
a : Any = os.path.join(UpperCAmelCase_ , (filename_prefix + '-' if filename_prefix else '') + 'vocab.txt')
with open(UpperCAmelCase_ , 'w') as f:
f.write('\n'.join(self.all_tokens))
return (vocab_file,)
@property
def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any]):
"""simple docstring"""
return self.get_vocab_size(with_added_tokens=UpperCAmelCase_)
def SCREAMING_SNAKE_CASE_ ( self : int , UpperCAmelCase_ : Union[List[str], List[AddedToken]] , UpperCAmelCase_ : bool = False):
"""simple docstring"""
return super()._add_tokens(UpperCAmelCase_ , special_tokens=UpperCAmelCase_)
| 610 | '''simple docstring'''
import importlib
import os
import sys
# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append(""".""")
def SCREAMING_SNAKE_CASE__ ( snake_case : Dict ) -> Optional[Any]:
"""simple docstring"""
a : Union[str, Any] = test_file.split(os.path.sep )
if components[0:2] != ["tests", "models"]:
raise ValueError(
'`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '
F"""{test_file} instead.""" )
a : int = components[-1]
if not test_fn.endswith('py' ):
raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead.""" )
if not test_fn.startswith('test_modeling_' ):
raise ValueError(
F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" )
a : Tuple = components[:-1] + [test_fn.replace('.py' , '' )]
a : Union[str, Any] = '.'.join(snake_case )
return test_module_path
def SCREAMING_SNAKE_CASE__ ( snake_case : List[Any] ) -> Tuple:
"""simple docstring"""
a : List[str] = get_module_path(snake_case )
a : Tuple = importlib.import_module(snake_case )
return test_module
def SCREAMING_SNAKE_CASE__ ( snake_case : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
a : Optional[int] = []
a : str = get_test_module(snake_case )
for attr in dir(snake_case ):
if attr.endswith('ModelTester' ):
tester_classes.append(getattr(snake_case , snake_case ) )
# sort with class names
return sorted(snake_case , key=lambda snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE__ ( snake_case : Tuple ) -> str:
"""simple docstring"""
a : Dict = []
a : List[str] = get_test_module(snake_case )
for attr in dir(snake_case ):
a : int = getattr(snake_case , snake_case )
# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
# `all_model_classes` is not empty (which also excludes other special classes).
a : Optional[Any] = getattr(snake_case , 'all_model_classes' , [] )
if len(snake_case ) > 0:
test_classes.append(snake_case )
# sort with class names
return sorted(snake_case , key=lambda snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE__ ( snake_case : Any ) -> Union[str, Any]:
"""simple docstring"""
a : Dict = get_test_classes(snake_case )
a : List[str] = set()
for test_class in test_classes:
model_classes.update(test_class.all_model_classes )
# sort with class names
return sorted(snake_case , key=lambda snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[Any] ) -> str:
"""simple docstring"""
a : Dict = test_class()
if hasattr(snake_case , 'setUp' ):
test.setUp()
a : Union[str, Any] = None
if hasattr(snake_case , 'model_tester' ):
# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
if test.model_tester is not None:
a : Tuple = test.model_tester.__class__
return model_tester
def SCREAMING_SNAKE_CASE__ ( snake_case : Dict , snake_case : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
a : Optional[int] = get_test_classes(snake_case )
a : str = []
for test_class in test_classes:
if model_class in test_class.all_model_classes:
target_test_classes.append(snake_case )
# sort with class names
return sorted(snake_case , key=lambda snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[Any] , snake_case : int ) -> Optional[int]:
"""simple docstring"""
a : Any = get_test_classes_for_model(snake_case , snake_case )
a : Tuple = []
for test_class in test_classes:
a : Any = get_model_tester_from_test_class(snake_case )
if tester_class is not None:
tester_classes.append(snake_case )
# sort with class names
return sorted(snake_case , key=lambda snake_case : x.__name__ )
def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[int] ) -> str:
"""simple docstring"""
a : Dict = get_test_classes(snake_case )
a : Optional[Any] = {test_class: get_model_tester_from_test_class(snake_case ) for test_class in test_classes}
return test_tester_mapping
def SCREAMING_SNAKE_CASE__ ( snake_case : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
a : Dict = get_model_classes(snake_case )
a : Optional[Any] = {
model_class: get_test_classes_for_model(snake_case , snake_case ) for model_class in model_classes
}
return model_test_mapping
def SCREAMING_SNAKE_CASE__ ( snake_case : str ) -> Optional[Any]:
"""simple docstring"""
a : str = get_model_classes(snake_case )
a : List[Any] = {
model_class: get_tester_classes_for_model(snake_case , snake_case ) for model_class in model_classes
}
return model_to_tester_mapping
def SCREAMING_SNAKE_CASE__ ( snake_case : Any ) -> Union[str, Any]:
"""simple docstring"""
if isinstance(snake_case , snake_case ):
return o
elif isinstance(snake_case , snake_case ):
return o.__name__
elif isinstance(snake_case , (list, tuple) ):
return [to_json(snake_case ) for x in o]
elif isinstance(snake_case , snake_case ):
return {to_json(snake_case ): to_json(snake_case ) for k, v in o.items()}
else:
return o
| 610 | 1 |
def lowerCAmelCase_ ( lowerCamelCase ):
__magic_name__ : int =current_set.copy()
for row_index, row in enumerate(UpperCamelCase__ ):
__magic_name__ : Union[str, Any] =row[0]
for column_index, column in enumerate(UpperCamelCase__ ):
if magnitude == 0:
__magic_name__ : Dict =column
continue
__magic_name__ : Optional[int] =column / magnitude
# Subtract to cancel term
__magic_name__ : Union[str, Any] =current_set[0]
__magic_name__ : Tuple =[first_row]
__magic_name__ : Union[str, Any] =current_set[1::]
for row in current_set:
__magic_name__ : str =[]
# If first term is 0, it is already in form we want, so we preserve it
if row[0] == 0:
final_set.append(UpperCamelCase__ )
continue
for column_index in range(len(UpperCamelCase__ ) ):
temp_row.append(first_row[column_index] - row[column_index] )
final_set.append(UpperCamelCase__ )
# Create next recursion iteration set
if len(final_set[0] ) != 3:
__magic_name__ : Union[str, Any] =final_set[0]
__magic_name__ : Optional[Any] =[]
__magic_name__ : Union[str, Any] =[]
for row in final_set[1::]:
current_first_column.append(row[0] )
next_iteration.append(row[1::] )
__magic_name__ : List[Any] =simplify(UpperCamelCase__ )
for i in range(len(UpperCamelCase__ ) ):
resultant[i].insert(0 , current_first_column[i] )
resultant.insert(0 , UpperCamelCase__ )
__magic_name__ : Any =resultant
return final_set
def lowerCAmelCase_ ( lowerCamelCase ):
if len(UpperCamelCase__ ) == 0:
raise IndexError("""solve_simultaneous() requires n lists of length n+1""" )
__magic_name__ : str =len(UpperCamelCase__ ) + 1
if any(len(UpperCamelCase__ ) != _length for item in equations ):
raise IndexError("""solve_simultaneous() requires n lists of length n+1""" )
for row in equations:
if any(not isinstance(UpperCamelCase__ , (int, float) ) for column in row ):
raise ValueError("""solve_simultaneous() requires lists of integers""" )
if len(UpperCamelCase__ ) == 1:
return [equations[0][-1] / equations[0][0]]
__magic_name__ : Tuple =equations.copy()
if any(0 in row for row in data_set ):
__magic_name__ : Any =data_set.copy()
__magic_name__ : Union[str, Any] =[]
for row_index, row in enumerate(UpperCamelCase__ ):
if 0 not in row:
__magic_name__ : Optional[Any] =data_set.pop(UpperCamelCase__ )
break
if not full_row:
raise ValueError("""solve_simultaneous() requires at least 1 full equation""" )
data_set.insert(0 , UpperCamelCase__ )
__magic_name__ : List[Any] =data_set.copy()
__magic_name__ : Optional[Any] =simplify(UpperCamelCase__ )
__magic_name__ : Optional[int] =simplified[::-1]
__magic_name__ : Dict =[]
for row in simplified:
__magic_name__ : Optional[int] =row[-1]
if not solutions:
if row[-2] == 0:
solutions.append(0 )
continue
solutions.append(current_solution / row[-2] )
continue
__magic_name__ : Union[str, Any] =row.copy()[: len(UpperCamelCase__ ) - 1 :]
while temp_row[0] == 0:
temp_row.pop(0 )
if len(UpperCamelCase__ ) == 0:
solutions.append(0 )
continue
__magic_name__ : str =temp_row[1::]
__magic_name__ : List[str] =temp_row[::-1]
for column_index, column in enumerate(UpperCamelCase__ ):
current_solution -= column * solutions[column_index]
solutions.append(UpperCamelCase__ )
__magic_name__ : Any =[]
for item in solutions:
final.append(float(round(UpperCamelCase__ , 5 ) ) )
return final[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
UpperCAmelCase_ : Any = [
[2, 1, 1, 1, 1, 4],
[1, 2, 1, 1, 1, 5],
[1, 1, 2, 1, 1, 6],
[1, 1, 1, 2, 1, 7],
[1, 1, 1, 1, 2, 8],
]
print(solve_simultaneous(eq))
print(solve_simultaneous([[4, 2]]))
| 21 |
import itertools
import random
import unittest
import numpy as np
from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
__A : Dict = random.Random()
def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__=1.0 , UpperCamelCase__=None , UpperCamelCase__=None ) -> Any:
'''simple docstring'''
if rng is None:
UpperCAmelCase = global_rng
UpperCAmelCase = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
class A_ (unittest.TestCase ):
def __init__( self , _A , _A=7 , _A=4_0_0 , _A=2_0_0_0 , _A=1 , _A=0.0 , _A=1_6_0_0_0 , _A=True , _A=True , ):
'''simple docstring'''
UpperCAmelCase = parent
UpperCAmelCase = batch_size
UpperCAmelCase = min_seq_length
UpperCAmelCase = max_seq_length
UpperCAmelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
UpperCAmelCase = feature_size
UpperCAmelCase = padding_value
UpperCAmelCase = sampling_rate
UpperCAmelCase = return_attention_mask
UpperCAmelCase = do_normalize
def _lowercase ( self ):
'''simple docstring'''
return {
"feature_size": self.feature_size,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def _lowercase ( self , _A=False , _A=False ):
'''simple docstring'''
def _flatten(_A ):
return list(itertools.chain(*_A ) )
if equal_length:
UpperCAmelCase = floats_list((self.batch_size, self.max_seq_length) )
else:
# make sure that inputs increase in size
UpperCAmelCase = [
_flatten(floats_list((x, self.feature_size) ) )
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff )
]
if numpify:
UpperCAmelCase = [np.asarray(_A ) for x in speech_inputs]
return speech_inputs
class A_ (a_ , unittest.TestCase ):
UpperCAmelCase__ = WavaVecaFeatureExtractor
def _lowercase ( self ):
'''simple docstring'''
UpperCAmelCase = WavaVecaFeatureExtractionTester(self )
def _lowercase ( self , _A ):
'''simple docstring'''
self.assertTrue(np.all(np.mean(_A , axis=0 ) < 1E-3 ) )
self.assertTrue(np.all(np.abs(np.var(_A , axis=0 ) - 1 ) < 1E-3 ) )
def _lowercase ( self ):
'''simple docstring'''
UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
# create three inputs of length 800, 1000, and 1200
UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
UpperCAmelCase = [np.asarray(_A ) for speech_input in speech_inputs]
# Test not batched input
UpperCAmelCase = feat_extract(speech_inputs[0] , return_tensors='''np''' ).input_values
UpperCAmelCase = feat_extract(np_speech_inputs[0] , return_tensors='''np''' ).input_values
self.assertTrue(np.allclose(_A , _A , atol=1E-3 ) )
# Test batched
UpperCAmelCase = feat_extract(_A , return_tensors='''np''' ).input_values
UpperCAmelCase = feat_extract(_A , return_tensors='''np''' ).input_values
for enc_seq_a, enc_seq_a in zip(_A , _A ):
self.assertTrue(np.allclose(_A , _A , atol=1E-3 ) )
# Test 2-D numpy arrays are batched.
UpperCAmelCase = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
UpperCAmelCase = np.asarray(_A )
UpperCAmelCase = feat_extract(_A , return_tensors='''np''' ).input_values
UpperCAmelCase = feat_extract(_A , return_tensors='''np''' ).input_values
for enc_seq_a, enc_seq_a in zip(_A , _A ):
self.assertTrue(np.allclose(_A , _A , atol=1E-3 ) )
def _lowercase ( self ):
'''simple docstring'''
UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
UpperCAmelCase = ['''longest''', '''max_length''', '''do_not_pad''']
UpperCAmelCase = [None, 1_6_0_0, None]
for max_length, padding in zip(_A , _A ):
UpperCAmelCase = feat_extract(_A , padding=_A , max_length=_A , return_tensors='''np''' )
UpperCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:8_0_0] )
self.assertTrue(input_values[0][8_0_0:].sum() < 1E-6 )
self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] )
self.assertTrue(input_values[0][1_0_0_0:].sum() < 1E-6 )
self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] )
def _lowercase ( self ):
'''simple docstring'''
UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
UpperCAmelCase = range(8_0_0 , 1_4_0_0 , 2_0_0 )
UpperCAmelCase = [floats_list((1, x) )[0] for x in lengths]
UpperCAmelCase = ['''longest''', '''max_length''', '''do_not_pad''']
UpperCAmelCase = [None, 1_6_0_0, None]
for max_length, padding in zip(_A , _A ):
UpperCAmelCase = feat_extract(_A , max_length=_A , padding=_A )
UpperCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0][:8_0_0] )
self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0] )
def _lowercase ( self ):
'''simple docstring'''
UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
UpperCAmelCase = feat_extract(
_A , truncation=_A , max_length=1_0_0_0 , padding='''max_length''' , return_tensors='''np''' )
UpperCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1] )
self._check_zero_mean_unit_variance(input_values[2] )
def _lowercase ( self ):
'''simple docstring'''
UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
UpperCAmelCase = feat_extract(
_A , truncation=_A , max_length=1_0_0_0 , padding='''longest''' , return_tensors='''np''' )
UpperCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length < longest -> then pad to max_length
self.assertTrue(input_values.shape == (3, 1_0_0_0) )
UpperCAmelCase = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )]
UpperCAmelCase = feat_extract(
_A , truncation=_A , max_length=2_0_0_0 , padding='''longest''' , return_tensors='''np''' )
UpperCAmelCase = processed.input_values
self._check_zero_mean_unit_variance(input_values[0, :8_0_0] )
self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0] )
self._check_zero_mean_unit_variance(input_values[2] )
# make sure that if max_length > longest -> then pad to longest
self.assertTrue(input_values.shape == (3, 1_2_0_0) )
@require_torch
def _lowercase ( self ):
'''simple docstring'''
import torch
UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
UpperCAmelCase = np.random.rand(1_0_0 ).astype(np.floataa )
UpperCAmelCase = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
UpperCAmelCase = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''' )
self.assertTrue(np_processed.input_values.dtype == np.floataa )
UpperCAmelCase = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''' )
self.assertTrue(pt_processed.input_values.dtype == torch.floataa )
@slow
@require_torch
def _lowercase ( self ):
'''simple docstring'''
for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
UpperCAmelCase = WavaVecaConfig.from_pretrained(_A )
UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained(_A )
# only "layer" feature extraction norm should make use of
# attention_mask
self.assertEqual(feat_extract.return_attention_mask , config.feat_extract_norm == '''layer''' )
| 130 | 0 |
"""simple docstring"""
import gc
import unittest
import torch
from parameterized import parameterized
from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class __UpperCAmelCase ( _UpperCAmelCase, _UpperCAmelCase, unittest.TestCase ):
'''simple docstring'''
lowercase : Any = AutoencoderKL
lowercase : Dict = 'sample'
lowercase : List[str] = 1E-2
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =4
_SCREAMING_SNAKE_CASE =3
_SCREAMING_SNAKE_CASE =(3_2, 3_2)
_SCREAMING_SNAKE_CASE =floats_tensor((batch_size, num_channels) + sizes ).to(__UpperCamelCase )
return {"sample": image}
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
return (3, 3_2, 3_2)
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
return (3, 3_2, 3_2)
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE ={
'''block_out_channels''': [3_2, 6_4],
'''in_channels''': 3,
'''out_channels''': 3,
'''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],
'''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],
'''latent_channels''': 4,
}
_SCREAMING_SNAKE_CASE =self.dummy_input
return init_dict, inputs_dict
def UpperCamelCase_ ( self ):
'''simple docstring'''
pass
def UpperCamelCase_ ( self ):
'''simple docstring'''
pass
@unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''' )
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.prepare_init_args_and_inputs_for_common()
_SCREAMING_SNAKE_CASE =self.model_class(**__UpperCamelCase )
model.to(__UpperCamelCase )
assert not model.is_gradient_checkpointing and model.training
_SCREAMING_SNAKE_CASE =model(**__UpperCamelCase ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model.zero_grad()
_SCREAMING_SNAKE_CASE =torch.randn_like(__UpperCamelCase )
_SCREAMING_SNAKE_CASE =(out - labels).mean()
loss.backward()
# re-instantiate the model now enabling gradient checkpointing
_SCREAMING_SNAKE_CASE =self.model_class(**__UpperCamelCase )
# clone model
model_a.load_state_dict(model.state_dict() )
model_a.to(__UpperCamelCase )
model_a.enable_gradient_checkpointing()
assert model_a.is_gradient_checkpointing and model_a.training
_SCREAMING_SNAKE_CASE =model_a(**__UpperCamelCase ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model_a.zero_grad()
_SCREAMING_SNAKE_CASE =(out_a - labels).mean()
loss_a.backward()
# compare the output and parameters gradients
self.assertTrue((loss - loss_a).abs() < 1E-5 )
_SCREAMING_SNAKE_CASE =dict(model.named_parameters() )
_SCREAMING_SNAKE_CASE =dict(model_a.named_parameters() )
for name, param in named_params.items():
self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) )
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 )
model.to(__UpperCamelCase )
_SCREAMING_SNAKE_CASE =model(**self.dummy_input )
assert image is not None, "Make sure output is not None"
def UpperCamelCase_ ( self ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' )
_SCREAMING_SNAKE_CASE =model.to(__UpperCamelCase )
model.eval()
if torch_device == "mps":
_SCREAMING_SNAKE_CASE =torch.manual_seed(0 )
else:
_SCREAMING_SNAKE_CASE =torch.Generator(device=__UpperCamelCase ).manual_seed(0 )
_SCREAMING_SNAKE_CASE =torch.randn(
1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , )
_SCREAMING_SNAKE_CASE =image.to(__UpperCamelCase )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model(__UpperCamelCase , sample_posterior=__UpperCamelCase , generator=__UpperCamelCase ).sample
_SCREAMING_SNAKE_CASE =output[0, -1, -3:, -3:].flatten().cpu()
# Since the VAE Gaussian prior's generator is seeded on the appropriate device,
# the expected output slices are not the same for CPU and GPU.
if torch_device == "mps":
_SCREAMING_SNAKE_CASE =torch.tensor(
[
-4.0078E-01,
-3.8323E-04,
-1.2681E-01,
-1.1462E-01,
2.0095E-01,
1.0893E-01,
-8.8247E-02,
-3.0361E-01,
-9.8644E-03,
] )
elif torch_device == "cpu":
_SCREAMING_SNAKE_CASE =torch.tensor(
[-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] )
else:
_SCREAMING_SNAKE_CASE =torch.tensor(
[-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] )
self.assertTrue(torch_all_close(__UpperCamelCase , __UpperCamelCase , rtol=1E-2 ) )
@slow
class __UpperCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase_ ( self , _A , _A ):
'''simple docstring'''
return f"""gaussian_noise_s={seed}_shape={"_".join([str(__UpperCamelCase ) for s in shape] )}.npy"""
def UpperCamelCase_ ( self ):
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCamelCase_ ( self , _A=0 , _A=(4, 3, 5_1_2, 5_1_2) , _A=False ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =torch.floataa if fpaa else torch.floataa
_SCREAMING_SNAKE_CASE =torch.from_numpy(load_hf_numpy(self.get_file_format(__UpperCamelCase , __UpperCamelCase ) ) ).to(__UpperCamelCase ).to(__UpperCamelCase )
return image
def UpperCamelCase_ ( self , _A="CompVis/stable-diffusion-v1-4" , _A=False ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE ='''fp16''' if fpaa else None
_SCREAMING_SNAKE_CASE =torch.floataa if fpaa else torch.floataa
_SCREAMING_SNAKE_CASE =AutoencoderKL.from_pretrained(
__UpperCamelCase , subfolder='''vae''' , torch_dtype=__UpperCamelCase , revision=__UpperCamelCase , )
model.to(__UpperCamelCase ).eval()
return model
def UpperCamelCase_ ( self , _A=0 ):
'''simple docstring'''
if torch_device == "mps":
return torch.manual_seed(__UpperCamelCase )
return torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase )
@parameterized.expand(
[
# fmt: off
[3_3, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[4_7, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
] )
def UpperCamelCase_ ( self , _A , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model()
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase )
_SCREAMING_SNAKE_CASE =self.get_generator(__UpperCamelCase )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model(__UpperCamelCase , generator=__UpperCamelCase , sample_posterior=__UpperCamelCase ).sample
assert sample.shape == image.shape
_SCREAMING_SNAKE_CASE =sample[-1, -2:, -2:, :2].flatten().float().cpu()
_SCREAMING_SNAKE_CASE =torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice )
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=3E-3 )
@parameterized.expand(
[
# fmt: off
[3_3, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
[4_7, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
# fmt: on
] )
@require_torch_gpu
def UpperCamelCase_ ( self , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model(fpaa=__UpperCamelCase )
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase , fpaa=__UpperCamelCase )
_SCREAMING_SNAKE_CASE =self.get_generator(__UpperCamelCase )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model(__UpperCamelCase , generator=__UpperCamelCase , sample_posterior=__UpperCamelCase ).sample
assert sample.shape == image.shape
_SCREAMING_SNAKE_CASE =sample[-1, -2:, :2, -2:].flatten().float().cpu()
_SCREAMING_SNAKE_CASE =torch.tensor(__UpperCamelCase )
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=1E-2 )
@parameterized.expand(
[
# fmt: off
[3_3, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[4_7, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
] )
def UpperCamelCase_ ( self , _A , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model()
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model(__UpperCamelCase ).sample
assert sample.shape == image.shape
_SCREAMING_SNAKE_CASE =sample[-1, -2:, -2:, :2].flatten().float().cpu()
_SCREAMING_SNAKE_CASE =torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice )
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=3E-3 )
@parameterized.expand(
[
# fmt: off
[1_3, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
[3_7, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
# fmt: on
] )
@require_torch_gpu
def UpperCamelCase_ ( self , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model()
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase , shape=(3, 4, 6_4, 6_4) )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model.decode(__UpperCamelCase ).sample
assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2]
_SCREAMING_SNAKE_CASE =sample[-1, -2:, :2, -2:].flatten().cpu()
_SCREAMING_SNAKE_CASE =torch.tensor(__UpperCamelCase )
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=1E-3 )
@parameterized.expand(
[
# fmt: off
[2_7, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
[1_6, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
# fmt: on
] )
@require_torch_gpu
def UpperCamelCase_ ( self , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model(fpaa=__UpperCamelCase )
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase , shape=(3, 4, 6_4, 6_4) , fpaa=__UpperCamelCase )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model.decode(__UpperCamelCase ).sample
assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2]
_SCREAMING_SNAKE_CASE =sample[-1, -2:, :2, -2:].flatten().float().cpu()
_SCREAMING_SNAKE_CASE =torch.tensor(__UpperCamelCase )
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=5E-3 )
@parameterized.expand([(1_3,), (1_6,), (2_7,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' )
def UpperCamelCase_ ( self , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model(fpaa=__UpperCamelCase )
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase , shape=(3, 4, 6_4, 6_4) , fpaa=__UpperCamelCase )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model.decode(__UpperCamelCase ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model.decode(__UpperCamelCase ).sample
assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2]
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=1E-1 )
@parameterized.expand([(1_3,), (1_6,), (3_7,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' )
def UpperCamelCase_ ( self , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model()
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase , shape=(3, 4, 6_4, 6_4) )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model.decode(__UpperCamelCase ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model.decode(__UpperCamelCase ).sample
assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2]
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=1E-2 )
@parameterized.expand(
[
# fmt: off
[3_3, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
[4_7, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
# fmt: on
] )
def UpperCamelCase_ ( self , _A , _A ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =self.get_sd_vae_model()
_SCREAMING_SNAKE_CASE =self.get_sd_image(__UpperCamelCase )
_SCREAMING_SNAKE_CASE =self.get_generator(__UpperCamelCase )
with torch.no_grad():
_SCREAMING_SNAKE_CASE =model.encode(__UpperCamelCase ).latent_dist
_SCREAMING_SNAKE_CASE =dist.sample(generator=__UpperCamelCase )
assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
_SCREAMING_SNAKE_CASE =sample[0, -1, -3:, -3:].flatten().cpu()
_SCREAMING_SNAKE_CASE =torch.tensor(__UpperCamelCase )
_SCREAMING_SNAKE_CASE =3E-3 if torch_device != '''mps''' else 1E-2
assert torch_all_close(__UpperCamelCase , __UpperCamelCase , atol=__UpperCamelCase )
| 719 |
"""simple docstring"""
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
UpperCAmelCase_ : Tuple = logging.get_logger(__name__)
UpperCAmelCase_ : Any = R'''
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
or scores for each vocabulary token after SoftMax.
kwargs (`Dict[str, Any]`, *optional*):
Additional stopping criteria specific kwargs.
Return:
`bool`. `False` indicates we should continue, `True` indicates we should stop.
'''
class __UpperCAmelCase ( _lowerCamelCase ):
'''simple docstring'''
@add_start_docstrings(_A )
def __call__( self , _A , _A , **_A ):
'''simple docstring'''
raise NotImplementedError('''StoppingCriteria needs to be subclassed''' )
class __UpperCAmelCase ( _lowerCamelCase ):
'''simple docstring'''
def __init__( self , _A , _A = None ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =max_length
_SCREAMING_SNAKE_CASE =max_position_embeddings
@add_start_docstrings(_A )
def __call__( self , _A , _A , **_A ):
'''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 __UpperCAmelCase ( _lowerCamelCase ):
'''simple docstring'''
def __init__( self , _A , _A ):
'''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.''' , _A , )
_SCREAMING_SNAKE_CASE =start_length
_SCREAMING_SNAKE_CASE =max_new_tokens
_SCREAMING_SNAKE_CASE =start_length + max_new_tokens
@add_start_docstrings(_A )
def __call__( self , _A , _A , **_A ):
'''simple docstring'''
return input_ids.shape[-1] >= self.max_length
class __UpperCAmelCase ( _lowerCamelCase ):
'''simple docstring'''
def __init__( self , _A , _A = None ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE =max_time
_SCREAMING_SNAKE_CASE =time.time() if initial_timestamp is None else initial_timestamp
@add_start_docstrings(_A )
def __call__( self , _A , _A , **_A ):
'''simple docstring'''
return time.time() - self.initial_timestamp > self.max_time
class __UpperCAmelCase ( _lowerCamelCase ):
'''simple docstring'''
@add_start_docstrings(_A )
def __call__( self , _A , _A , **_A ):
'''simple docstring'''
return any(criteria(_A , _A ) for criteria in self )
@property
def UpperCamelCase_ ( self ):
'''simple docstring'''
for stopping_criterium in self:
if isinstance(_A , _A ):
return stopping_criterium.max_length
elif isinstance(_A , _A ):
return stopping_criterium.max_length
return None
def _lowerCAmelCase(a : StoppingCriteriaList , a : int ) -> StoppingCriteriaList:
_SCREAMING_SNAKE_CASE =stopping_criteria.max_length
_SCREAMING_SNAKE_CASE =deepcopy(a )
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''' , a )
elif stopping_max_length is None:
new_stopping_criteria.append(MaxLengthCriteria(max_length=a ) )
return new_stopping_criteria
| 165 | 0 |
from __future__ import annotations
from math import gcd
def __snake_case ( __UpperCamelCase : int ,__UpperCamelCase : int = 2 ,__UpperCamelCase : int = 1 ,__UpperCamelCase : int = 3 ,):
"""simple docstring"""
if num < 2:
raise ValueError("The input value cannot be less than 2" )
# Because of the relationship between ``f(f(x))`` and ``f(x)``, this
# algorithm struggles to find factors that are divisible by two.
# As a workaround, we specifically check for two and even inputs.
# See: https://math.stackexchange.com/a/2856214/165820
if num > 2 and num % 2 == 0:
return 2
# Pollard's Rho algorithm requires a function that returns pseudorandom
# values between 0 <= X < ``num``. It doesn't need to be random in the
# sense that the output value is cryptographically secure or difficult
# to calculate, it only needs to be random in the sense that all output
# values should be equally likely to appear.
# For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
# However, the success of Pollard's algorithm isn't guaranteed and is
# determined in part by the initial seed and the chosen random function.
# To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
# where ``C`` is a value that we can modify between each attempt.
def rand_fn(__UpperCamelCase : int ,__UpperCamelCase : int ,__UpperCamelCase : int ) -> int:
return (pow(__UpperCamelCase ,2 ) + step) % modulus
for _ in range(__UpperCamelCase ):
# These track the position within the cycle detection logic.
A_ = seed
A_ = seed
while True:
# At each iteration, the tortoise moves one step and the hare moves two.
A_ = rand_fn(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase )
A_ = rand_fn(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase )
A_ = rand_fn(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase )
# At some point both the tortoise and the hare will enter a cycle whose
# length ``p`` is a divisor of ``num``. Once in that cycle, at some point
# the tortoise and hare will end up on the same value modulo ``p``.
# We can detect when this happens because the position difference between
# the tortoise and the hare will share a common divisor with ``num``.
A_ = gcd(hare - tortoise ,__UpperCamelCase )
if divisor == 1:
# No common divisor yet, just keep searching.
continue
else:
# We found a common divisor!
if divisor == num:
# Unfortunately, the divisor is ``num`` itself and is useless.
break
else:
# The divisor is a nontrivial factor of ``num``!
return divisor
# If we made it here, then this attempt failed.
# We need to pick a new starting seed for the tortoise and hare
# in addition to a new step value for the random function.
# To keep this example implementation deterministic, the
# new values will be generated based on currently available
# values instead of using something like ``random.randint``.
# We can use the hare's position as the new seed.
# This is actually what Richard Brent's the "optimized" variant does.
A_ = hare
# The new step value for the random function can just be incremented.
# At first the results will be similar to what the old function would
# have produced, but the value will quickly diverge after a bit.
step += 1
# We haven't found a divisor within the requested number of attempts.
# We were unlucky or ``num`` itself is actually prime.
return None
if __name__ == "__main__":
import argparse
__a :List[Any] = argparse.ArgumentParser()
parser.add_argument(
'num',
type=int,
help='The value to find a divisor of',
)
parser.add_argument(
'--attempts',
type=int,
default=3,
help='The number of attempts before giving up',
)
__a :int = parser.parse_args()
__a :List[Any] = pollard_rho(args.num, attempts=args.attempts)
if divisor is None:
print(F"{args.num} is probably prime")
else:
__a :List[str] = args.num // divisor
print(F"{args.num} = {divisor} * {quotient}") | 86 |
'''simple docstring'''
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import AutoTokenizer, BarkProcessor
from transformers.testing_utils import require_torch, slow
@require_torch
class UpperCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def UpperCamelCase( self ) -> Any:
'''simple docstring'''
lowerCamelCase_ = 'ylacombe/bark-small'
lowerCamelCase_ = tempfile.mkdtemp()
lowerCamelCase_ = 'en_speaker_1'
lowerCamelCase_ = 'This is a test string'
lowerCamelCase_ = 'speaker_embeddings_path.json'
lowerCamelCase_ = 'speaker_embeddings'
def UpperCamelCase( self , **SCREAMING_SNAKE_CASE_ ) -> int:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE_ )
def UpperCamelCase( self ) -> Optional[Any]:
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def UpperCamelCase( self ) -> Dict:
'''simple docstring'''
lowerCamelCase_ = self.get_tokenizer()
lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ )
processor.save_pretrained(self.tmpdirname )
lowerCamelCase_ = BarkProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
@slow
def UpperCamelCase( self ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
processor.save_pretrained(
self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , )
lowerCamelCase_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' )
lowerCamelCase_ = BarkProcessor.from_pretrained(
self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
def UpperCamelCase( self ) -> List[str]:
'''simple docstring'''
lowerCamelCase_ = BarkProcessor.from_pretrained(
pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , )
lowerCamelCase_ = 35
lowerCamelCase_ = 2
lowerCamelCase_ = 8
lowerCamelCase_ = {
'semantic_prompt': np.ones(SCREAMING_SNAKE_CASE_ ),
'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ),
'fine_prompt': np.ones((nb_codebooks_total, seq_len) ),
}
# test providing already loaded voice_preset
lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = inputs['history_prompt']
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() )
# test loading voice preset from npz file
lowerCamelCase_ = os.path.join(self.tmpdirname , 'file.npz' )
np.savez(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = processor(text=self.input_string , voice_preset=SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = inputs['history_prompt']
for key in voice_preset:
self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(SCREAMING_SNAKE_CASE_ , np.array([] ) ).tolist() )
# test loading voice preset from the hub
lowerCamelCase_ = processor(text=self.input_string , voice_preset=self.voice_preset )
def UpperCamelCase( self ) -> List[Any]:
'''simple docstring'''
lowerCamelCase_ = self.get_tokenizer()
lowerCamelCase_ = BarkProcessor(tokenizer=SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = processor(text=self.input_string )
lowerCamelCase_ = tokenizer(
self.input_string , padding='max_length' , max_length=256 , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
| 42 | 0 |
'''simple docstring'''
def __lowerCamelCase ( _UpperCamelCase : int = 1000 ):
'''simple docstring'''
UpperCAmelCase_ = 2**power
UpperCAmelCase_ = str(_UpperCamelCase )
UpperCAmelCase_ = list(_UpperCamelCase )
UpperCAmelCase_ = 0
for i in list_num:
sum_of_num += int(_UpperCamelCase )
return sum_of_num
if __name__ == "__main__":
lowercase__ : Tuple = int(input("Enter the power of 2: ").strip())
print("2 ^ ", power, " = ", 2**power)
lowercase__ : Optional[Any] = solution(power)
print("Sum of the digits is: ", result)
| 703 | '''simple docstring'''
from ...utils import logging
from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel
from .configuration_mta import MTaConfig
lowercase__ : Dict = logging.get_logger(__name__)
lowercase__ : List[Any] = "T5Config"
class lowerCamelCase ( lowerCamelCase ):
'''simple docstring'''
lowerCAmelCase__ = '''mt5'''
lowerCAmelCase__ = MTaConfig
class lowerCamelCase ( lowerCamelCase ):
'''simple docstring'''
lowerCAmelCase__ = '''mt5'''
lowerCAmelCase__ = MTaConfig
class lowerCamelCase ( lowerCamelCase ):
'''simple docstring'''
lowerCAmelCase__ = '''mt5'''
lowerCAmelCase__ = MTaConfig
| 43 | 0 |
'''simple docstring'''
import math
import os
import sys
def lowerCAmelCase_ ( snake_case_ : str ) -> str:
'''simple docstring'''
UpperCAmelCase_ = ""
try:
with open(snake_case_ , "rb" ) as binary_file:
UpperCAmelCase_ = binary_file.read()
for dat in data:
UpperCAmelCase_ = f"""{dat:08b}"""
result += curr_byte
return result
except OSError:
print("File not accessible" )
sys.exit()
def lowerCAmelCase_ ( snake_case_ : dict[str, str] , snake_case_ : str , snake_case_ : int , snake_case_ : str ) -> None:
'''simple docstring'''
lexicon.pop(snake_case_ )
UpperCAmelCase_ = last_match_id
if math.loga(snake_case_ ).is_integer():
for curr_key in lexicon:
UpperCAmelCase_ = "0" + lexicon[curr_key]
UpperCAmelCase_ = bin(snake_case_ )[2:]
def lowerCAmelCase_ ( snake_case_ : str ) -> str:
'''simple docstring'''
UpperCAmelCase_ = {"0": "0", "1": "1"}
UpperCAmelCase_ , UpperCAmelCase_ = "", ""
UpperCAmelCase_ = len(snake_case_ )
for i in range(len(snake_case_ ) ):
curr_string += data_bits[i]
if curr_string not in lexicon:
continue
UpperCAmelCase_ = lexicon[curr_string]
result += last_match_id
add_key_to_lexicon(snake_case_ , snake_case_ , snake_case_ , snake_case_ )
index += 1
UpperCAmelCase_ = ""
while curr_string != "" and curr_string not in lexicon:
curr_string += "0"
if curr_string != "":
UpperCAmelCase_ = lexicon[curr_string]
result += last_match_id
return result
def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> str:
'''simple docstring'''
UpperCAmelCase_ = os.path.getsize(snake_case_ )
UpperCAmelCase_ = bin(snake_case_ )[2:]
UpperCAmelCase_ = len(snake_case_ )
return "0" * (length_length - 1) + file_length_binary + compressed
def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None:
'''simple docstring'''
UpperCAmelCase_ = 8
try:
with open(snake_case_ , "wb" ) as opened_file:
UpperCAmelCase_ = [
to_write[i : i + byte_length]
for i in range(0 , len(snake_case_ ) , snake_case_ )
]
if len(result_byte_array[-1] ) % byte_length == 0:
result_byte_array.append("10000000" )
else:
result_byte_array[-1] += "1" + "0" * (
byte_length - len(result_byte_array[-1] ) - 1
)
for elem in result_byte_array:
opened_file.write(int(snake_case_ , 2 ).to_bytes(1 , byteorder="big" ) )
except OSError:
print("File not accessible" )
sys.exit()
def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None:
'''simple docstring'''
UpperCAmelCase_ = read_file_binary(snake_case_ )
UpperCAmelCase_ = compress_data(snake_case_ )
UpperCAmelCase_ = add_file_length(snake_case_ , snake_case_ )
write_file_binary(snake_case_ , snake_case_ )
if __name__ == "__main__":
compress(sys.argv[1], sys.argv[2])
| 78 | """simple docstring"""
import unittest
from transformers import AutoTokenizer, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
if is_flax_available():
import jax.numpy as jnp
from transformers import FlaxXLMRobertaModel
@require_sentencepiece
@require_tokenizers
@require_flax
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@slow
def _lowerCAmelCase ( self : int ) -> Optional[Any]:
'''simple docstring'''
a__ = FlaxXLMRobertaModel.from_pretrained('xlm-roberta-base' )
a__ = AutoTokenizer.from_pretrained('xlm-roberta-base' )
a__ = 'The dog is cute and lives in the garden house'
a__ = jnp.array([tokenizer.encode(_snake_case )] )
a__ = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim
a__ = jnp.array(
[[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] )
a__ = model(_snake_case )['last_hidden_state']
self.assertEqual(output.shape , _snake_case )
# compare the actual values for a slice of last dim
self.assertTrue(jnp.allclose(output[:, :, -1] , _snake_case , atol=1E-3 ) )
| 232 | 0 |
'''simple docstring'''
import gc
import unittest
import numpy as np
import torch
from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
@slow
@require_torch_gpu
class UpperCAmelCase ( unittest.TestCase ):
def __lowerCamelCase ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __lowerCamelCase ( self ):
__UpperCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' )
__UpperCAmelCase = sd_pipe.to(__A )
sd_pipe.set_progress_bar_config(disable=__A )
sd_pipe.set_scheduler('sample_euler' )
__UpperCAmelCase = 'A painting of a squirrel eating a burger'
__UpperCAmelCase = torch.manual_seed(0 )
__UpperCAmelCase = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' )
__UpperCAmelCase = output.images
__UpperCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
__UpperCAmelCase = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __lowerCamelCase ( self ):
__UpperCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' )
__UpperCAmelCase = sd_pipe.to(__A )
sd_pipe.set_progress_bar_config(disable=__A )
sd_pipe.set_scheduler('sample_euler' )
__UpperCAmelCase = 'A painting of a squirrel eating a burger'
__UpperCAmelCase = torch.manual_seed(0 )
__UpperCAmelCase = sd_pipe([prompt] , generator=__A , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' )
__UpperCAmelCase = output.images
__UpperCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
__UpperCAmelCase = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1
def __lowerCamelCase ( self ):
__UpperCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' )
__UpperCAmelCase = sd_pipe.to(__A )
sd_pipe.set_progress_bar_config(disable=__A )
sd_pipe.set_scheduler('sample_dpmpp_2m' )
__UpperCAmelCase = 'A painting of a squirrel eating a burger'
__UpperCAmelCase = torch.manual_seed(0 )
__UpperCAmelCase = sd_pipe(
[prompt] , generator=__A , guidance_scale=7.5 , num_inference_steps=15 , output_type='np' , use_karras_sigmas=__A , )
__UpperCAmelCase = output.images
__UpperCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
__UpperCAmelCase = np.array(
[0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 617 |
'''simple docstring'''
import math
from typing import Callable, List, Optional, Union
import numpy as np
import PIL
import torch
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=[] )-> Any:
__UpperCAmelCase = size[0] - overlap_pixels * 2
__UpperCAmelCase = size[1] - overlap_pixels * 2
for letter in ["l", "r"]:
if letter in remove_borders:
size_x += overlap_pixels
for letter in ["t", "b"]:
if letter in remove_borders:
size_y += overlap_pixels
__UpperCAmelCase = np.ones((size_y, size_x) , dtype=np.uinta ) * 2_55
__UpperCAmelCase = np.pad(_lowerCAmelCase , mode='linear_ramp' , pad_width=_lowerCAmelCase , end_values=0 )
if "l" in remove_borders:
__UpperCAmelCase = mask[:, overlap_pixels : mask.shape[1]]
if "r" in remove_borders:
__UpperCAmelCase = mask[:, 0 : mask.shape[1] - overlap_pixels]
if "t" in remove_borders:
__UpperCAmelCase = mask[overlap_pixels : mask.shape[0], :]
if "b" in remove_borders:
__UpperCAmelCase = mask[0 : mask.shape[0] - overlap_pixels, :]
return mask
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )-> Any:
return max(_lowerCAmelCase , min(_lowerCAmelCase , _lowerCAmelCase ) )
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )-> Dict:
return (
clamp(rect[0] , min[0] , max[0] ),
clamp(rect[1] , min[1] , max[1] ),
clamp(rect[2] , min[0] , max[0] ),
clamp(rect[3] , min[1] , max[1] ),
)
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )-> Dict:
__UpperCAmelCase = list(_lowerCAmelCase )
rect[0] -= overlap
rect[1] -= overlap
rect[2] += overlap
rect[3] += overlap
__UpperCAmelCase = clamp_rect(_lowerCAmelCase , [0, 0] , [image_size[0], image_size[1]] )
return rect
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )-> Tuple:
__UpperCAmelCase = Image.new('RGB' , (tile.size[0] + original_slice, tile.size[1]) )
result.paste(
original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop(
(slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , )
result.paste(_lowerCAmelCase , (original_slice, 0) )
return result
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase )-> List[Any]:
__UpperCAmelCase = (original_image_slice * 4, 0, tile.size[0], tile.size[1])
__UpperCAmelCase = tile.crop(_lowerCAmelCase )
return tile
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase )-> Optional[int]:
__UpperCAmelCase = n % d
return n - divisor
class UpperCAmelCase ( UpperCAmelCase_ ):
def __init__( self , __A , __A , __A , __A , __A , __A , __A = 350 , ):
super().__init__(
vae=__A , text_encoder=__A , tokenizer=__A , unet=__A , low_res_scheduler=__A , scheduler=__A , max_noise_level=__A , )
def __lowerCamelCase ( self , __A , __A , __A , __A , __A , __A , __A , **__A ):
torch.manual_seed(0 )
__UpperCAmelCase = (
min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ),
min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ),
min(image.size[0] , (x + 1) * tile_size ),
min(image.size[1] , (y + 1) * tile_size ),
)
__UpperCAmelCase = add_overlap_rect(__A , __A , image.size )
__UpperCAmelCase = image.crop(__A )
__UpperCAmelCase = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
__UpperCAmelCase = translated_slice_x - (original_image_slice / 2)
__UpperCAmelCase = max(0 , __A )
__UpperCAmelCase = squeeze_tile(__A , __A , __A , __A )
__UpperCAmelCase = to_input.size
__UpperCAmelCase = to_input.resize((tile_size, tile_size) , Image.BICUBIC )
__UpperCAmelCase = super(__A , self ).__call__(image=__A , **__A ).images[0]
__UpperCAmelCase = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC )
__UpperCAmelCase = unsqueeze_tile(__A , __A )
__UpperCAmelCase = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC )
__UpperCAmelCase = []
if x == 0:
remove_borders.append('l' )
elif crop_rect[2] == image.size[0]:
remove_borders.append('r' )
if y == 0:
remove_borders.append('t' )
elif crop_rect[3] == image.size[1]:
remove_borders.append('b' )
__UpperCAmelCase = Image.fromarray(
make_transparency_mask(
(upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__A ) , mode='L' , )
final_image.paste(
__A , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __A )
@torch.no_grad()
def __call__( self , __A , __A , __A = 75 , __A = 9.0 , __A = 50 , __A = None , __A = 1 , __A = 0.0 , __A = None , __A = None , __A = None , __A = 1 , __A = 128 , __A = 32 , __A = 32 , ):
__UpperCAmelCase = Image.new('RGB' , (image.size[0] * 4, image.size[1] * 4) )
__UpperCAmelCase = math.ceil(image.size[0] / tile_size )
__UpperCAmelCase = math.ceil(image.size[1] / tile_size )
__UpperCAmelCase = tcx * tcy
__UpperCAmelCase = 0
for y in range(__A ):
for x in range(__A ):
self._process_tile(
__A , __A , __A , __A , __A , __A , __A , prompt=__A , num_inference_steps=__A , guidance_scale=__A , noise_level=__A , negative_prompt=__A , num_images_per_prompt=__A , eta=__A , generator=__A , latents=__A , )
current_count += 1
if callback is not None:
callback({'progress': current_count / total_tile_count, 'image': final_image} )
return final_image
def _lowerCAmelCase ( )-> str:
# Run a demo
__UpperCAmelCase = 'stabilityai/stable-diffusion-x4-upscaler'
__UpperCAmelCase = StableDiffusionTiledUpscalePipeline.from_pretrained(_lowerCAmelCase , revision='fp16' , torch_dtype=torch.floataa )
__UpperCAmelCase = pipe.to('cuda' )
__UpperCAmelCase = Image.open('../../docs/source/imgs/diffusers_library.jpg' )
def callback(_lowerCAmelCase ):
print(F'progress: {obj["progress"]:.4f}' )
obj["image"].save('diffusers_library_progress.jpg' )
__UpperCAmelCase = pipe(image=_lowerCAmelCase , prompt='Black font, white background, vector' , noise_level=40 , callback=_lowerCAmelCase )
final_image.save('diffusers_library.jpg' )
if __name__ == "__main__":
main()
| 617 | 1 |
"""simple docstring"""
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
_UpperCamelCase : int = logging.get_logger(__name__)
_UpperCamelCase : Any = r'''
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
or scores for each vocabulary token after SoftMax.
kwargs (`Dict[str, Any]`, *optional*):
Additional stopping criteria specific kwargs.
Return:
`bool`. `False` indicates we should continue, `True` indicates we should stop.
'''
class UpperCAmelCase_ ( _UpperCamelCase):
@add_start_docstrings(a_ )
def __call__( self , a , a , **a ) -> str:
raise NotImplementedError('StoppingCriteria needs to be subclassed' )
class UpperCAmelCase_ ( _UpperCamelCase):
def __init__( self , a , a = None ) -> int:
lowercase__ : Any = max_length
lowercase__ : Union[str, Any] = max_position_embeddings
@add_start_docstrings(a_ )
def __call__( self , a , a , **a ) -> int:
lowercase__ : Optional[Any] = input_ids.shape[-1]
lowercase__ : Tuple = 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 UpperCAmelCase_ ( _UpperCamelCase):
def __init__( self , a , a ) -> int:
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.' , a_ , )
lowercase__ : List[str] = start_length
lowercase__ : List[Any] = max_new_tokens
lowercase__ : int = start_length + max_new_tokens
@add_start_docstrings(a_ )
def __call__( self , a , a , **a ) -> Dict:
return input_ids.shape[-1] >= self.max_length
class UpperCAmelCase_ ( _UpperCamelCase):
def __init__( self , a , a = None ) -> List[Any]:
lowercase__ : List[str] = max_time
lowercase__ : Optional[int] = time.time() if initial_timestamp is None else initial_timestamp
@add_start_docstrings(a_ )
def __call__( self , a , a , **a ) -> Tuple:
return time.time() - self.initial_timestamp > self.max_time
class UpperCAmelCase_ ( _UpperCamelCase):
@add_start_docstrings(a_ )
def __call__( self , a , a , **a ) -> Optional[int]:
return any(criteria(a_ , a_ ) for criteria in self )
@property
def _UpperCAmelCase ( self ) -> List[str]:
for stopping_criterium in self:
if isinstance(a_ , a_ ):
return stopping_criterium.max_length
elif isinstance(a_ , a_ ):
return stopping_criterium.max_length
return None
def a_ ( _lowerCAmelCase : StoppingCriteriaList , _lowerCAmelCase : int ):
'''simple docstring'''
lowercase__ : Optional[Any] = stopping_criteria.max_length
lowercase__ : List[str] = deepcopy(_UpperCAmelCase )
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' , _UpperCAmelCase )
elif stopping_max_length is None:
new_stopping_criteria.append(MaxLengthCriteria(max_length=_UpperCAmelCase ) )
return new_stopping_criteria
| 599 |
'''simple docstring'''
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ):
def A ( self : Optional[Any] , a_ : str ):
"""simple docstring"""
with open(a_ , encoding="utf-8" ) as input_file:
__snake_case = re.compile(r"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" )
__snake_case = input_file.read()
__snake_case = regexp.search(a_ )
return match
def A ( self : Any , a_ : str ):
"""simple docstring"""
with open(a_ , encoding="utf-8" ) as input_file:
__snake_case = re.compile(r"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL )
__snake_case = input_file.read()
# use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
__snake_case = regexp.finditer(a_ )
__snake_case = [match for match in matches if match is not None and match.group(1 ) is not None]
return matches[0] if matches else None
def A ( self : Optional[int] ):
"""simple docstring"""
__snake_case = Path("./datasets" )
__snake_case = list(dataset_paths.absolute().glob("**/*.py" ) )
for dataset in dataset_files:
if self._no_encoding_on_file_open(str(a_ ) ):
raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' )
def A ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = Path("./datasets" )
__snake_case = list(dataset_paths.absolute().glob("**/*.py" ) )
for dataset in dataset_files:
if self._no_print_statements(str(a_ ) ):
raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
| 69 | 0 |
'''simple docstring'''
from math import pi, sqrt
def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ):
if num <= 0:
raise ValueError('math domain error' )
if num > 171.5:
raise OverflowError('math range error' )
elif num - int(SCREAMING_SNAKE_CASE_ ) not in (0, 0.5):
raise NotImplementedError('num must be an integer or a half-integer' )
elif num == 0.5:
return sqrt(SCREAMING_SNAKE_CASE_ )
else:
return 1.0 if num == 1 else (num - 1) * gamma(num - 1 )
def _UpperCamelCase ( ):
assert gamma(0.5 ) == sqrt(SCREAMING_SNAKE_CASE_ )
assert gamma(1 ) == 1.0
assert gamma(2 ) == 1.0
if __name__ == "__main__":
from doctest import testmod
testmod()
_A = 1.0
while num:
_A = float(input('Gamma of: '))
print(F"""gamma({num}) = {gamma(num)}""")
print('\nEnter 0 to exit...')
| 700 | '''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_A = {
'configuration_bigbird_pegasus': [
'BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP',
'BigBirdPegasusConfig',
'BigBirdPegasusOnnxConfig',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A = [
'BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST',
'BigBirdPegasusForCausalLM',
'BigBirdPegasusForConditionalGeneration',
'BigBirdPegasusForQuestionAnswering',
'BigBirdPegasusForSequenceClassification',
'BigBirdPegasusModel',
'BigBirdPegasusPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_bigbird_pegasus import (
BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP,
BigBirdPegasusConfig,
BigBirdPegasusOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_bigbird_pegasus import (
BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST,
BigBirdPegasusForCausalLM,
BigBirdPegasusForConditionalGeneration,
BigBirdPegasusForQuestionAnswering,
BigBirdPegasusForSequenceClassification,
BigBirdPegasusModel,
BigBirdPegasusPreTrainedModel,
)
else:
import sys
_A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 438 | 0 |
'''simple docstring'''
import gc
import unittest
from parameterized import parameterized
from diffusers import FlaxUNetaDConditionModel
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow
if is_flax_available():
import jax
import jax.numpy as jnp
@slow
@require_flax
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase):
def UpperCAmelCase_ ( self , A_ , A_ )-> Optional[Any]:
'''simple docstring'''
return F'''gaussian_noise_s={seed}_shape={"_".join([str(A_ ) for s in shape] )}.npy'''
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
super().tearDown()
gc.collect()
def UpperCAmelCase_ ( self , A_=0 , A_=(4, 4, 64, 64) , A_=False )-> List[str]:
'''simple docstring'''
UpperCamelCase = jnp.bfloataa if fpaa else jnp.floataa
UpperCamelCase = jnp.array(load_hf_numpy(self.get_file_format(A_ , A_ ) ) , dtype=A_ )
return image
def UpperCAmelCase_ ( self , A_=False , A_="CompVis/stable-diffusion-v1-4" )-> Union[str, Any]:
'''simple docstring'''
UpperCamelCase = jnp.bfloataa if fpaa else jnp.floataa
UpperCamelCase = 'bf16' if fpaa else None
UpperCamelCase , UpperCamelCase = FlaxUNetaDConditionModel.from_pretrained(
A_ , subfolder='unet' , dtype=A_ , revision=A_ )
return model, params
def UpperCAmelCase_ ( self , A_=0 , A_=(4, 77, 768) , A_=False )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = jnp.bfloataa if fpaa else jnp.floataa
UpperCamelCase = jnp.array(load_hf_numpy(self.get_file_format(A_ , A_ ) ) , dtype=A_ )
return hidden_states
@parameterized.expand(
[
# fmt: off
[83, 4, [-0.2_323, -0.1_304, 0.0_813, -0.3_093, -0.0_919, -0.1_571, -0.1_125, -0.5_806]],
[17, 0.55, [-0.0_831, -0.2_443, 0.0_901, -0.0_919, 0.3_396, 0.0_103, -0.3_743, 0.0_701]],
[8, 0.89, [-0.4_863, 0.0_859, 0.0_875, -0.1_658, 0.9_199, -0.0_114, 0.4_839, 0.4_639]],
[3, 1000, [-0.5_649, 0.2_402, -0.5_518, 0.1_248, 1.1_328, -0.2_443, -0.0_325, -1.0_078]],
# fmt: on
] )
def UpperCAmelCase_ ( self , A_ , A_ , A_ )-> List[Any]:
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.get_unet_model(model_id='CompVis/stable-diffusion-v1-4' , fpaa=A_ )
UpperCamelCase = self.get_latents(A_ , fpaa=A_ )
UpperCamelCase = self.get_encoder_hidden_states(A_ , fpaa=A_ )
UpperCamelCase = model.apply(
{'params': params} , A_ , jnp.array(A_ , dtype=jnp.intaa ) , encoder_hidden_states=A_ , ).sample
assert sample.shape == latents.shape
UpperCamelCase = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa )
UpperCamelCase = jnp.array(A_ , dtype=jnp.floataa )
# Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware
assert jnp.allclose(A_ , A_ , atol=1e-2 )
@parameterized.expand(
[
# fmt: off
[83, 4, [0.1_514, 0.0_807, 0.1_624, 0.1_016, -0.1_896, 0.0_263, 0.0_677, 0.2_310]],
[17, 0.55, [0.1_164, -0.0_216, 0.0_170, 0.1_589, -0.3_120, 0.1_005, -0.0_581, -0.1_458]],
[8, 0.89, [-0.1_758, -0.0_169, 0.1_004, -0.1_411, 0.1_312, 0.1_103, -0.1_996, 0.2_139]],
[3, 1000, [0.1_214, 0.0_352, -0.0_731, -0.1_562, -0.0_994, -0.0_906, -0.2_340, -0.0_539]],
# fmt: on
] )
def UpperCAmelCase_ ( self , A_ , A_ , A_ )-> Any:
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.get_unet_model(model_id='stabilityai/stable-diffusion-2' , fpaa=A_ )
UpperCamelCase = self.get_latents(A_ , shape=(4, 4, 96, 96) , fpaa=A_ )
UpperCamelCase = self.get_encoder_hidden_states(A_ , shape=(4, 77, 1024) , fpaa=A_ )
UpperCamelCase = model.apply(
{'params': params} , A_ , jnp.array(A_ , dtype=jnp.intaa ) , encoder_hidden_states=A_ , ).sample
assert sample.shape == latents.shape
UpperCamelCase = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa )
UpperCamelCase = jnp.array(A_ , dtype=jnp.floataa )
# Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware
assert jnp.allclose(A_ , A_ , atol=1e-2 )
| 3 |
'''simple docstring'''
import inspect
import unittest
from datasets import load_dataset
from packaging import version
from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_MAPPING,
BeitForImageClassification,
BeitForMaskedImageModeling,
BeitForSemanticSegmentation,
BeitModel,
)
from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
import PIL
from PIL import Image
from transformers import BeitImageProcessor
class SCREAMING_SNAKE_CASE__ :
def __init__( self , A_ , A_=100 , A_=13 , A_=30 , A_=2 , A_=3 , A_=True , A_=True , A_=32 , A_=4 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=10 , A_=0.02 , A_=3 , A_=None , A_=[0, 1, 2, 3] , )-> Any:
'''simple docstring'''
UpperCamelCase = parent
UpperCamelCase = 100
UpperCamelCase = batch_size
UpperCamelCase = image_size
UpperCamelCase = patch_size
UpperCamelCase = num_channels
UpperCamelCase = is_training
UpperCamelCase = use_labels
UpperCamelCase = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = intermediate_size
UpperCamelCase = hidden_act
UpperCamelCase = hidden_dropout_prob
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = type_sequence_label_size
UpperCamelCase = initializer_range
UpperCamelCase = scope
UpperCamelCase = out_indices
UpperCamelCase = num_labels
# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
UpperCamelCase = (image_size // patch_size) ** 2
UpperCamelCase = num_patches + 1
def UpperCAmelCase_ ( self )-> List[str]:
'''simple docstring'''
UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase = None
UpperCamelCase = None
if self.use_labels:
UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
UpperCamelCase = self.get_config()
return config, pixel_values, labels, pixel_labels
def UpperCAmelCase_ ( self )-> Dict:
'''simple docstring'''
return BeitConfig(
vocab_size=self.vocab_size , 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=A_ , initializer_range=self.initializer_range , out_indices=self.out_indices , )
def UpperCAmelCase_ ( self , A_ , A_ , A_ , A_ )-> List[str]:
'''simple docstring'''
UpperCamelCase = BeitModel(config=A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase_ ( self , A_ , A_ , A_ , A_ )-> Any:
'''simple docstring'''
UpperCamelCase = BeitForMaskedImageModeling(config=A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) )
def UpperCAmelCase_ ( self , A_ , A_ , A_ , A_ )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = self.type_sequence_label_size
UpperCamelCase = BeitForImageClassification(A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ , labels=A_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
UpperCamelCase = 1
UpperCamelCase = BeitForImageClassification(A_ )
model.to(A_ )
model.eval()
UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
UpperCamelCase = model(A_ , labels=A_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def UpperCAmelCase_ ( self , A_ , A_ , A_ , A_ )-> Optional[Any]:
'''simple docstring'''
UpperCamelCase = self.num_labels
UpperCamelCase = BeitForSemanticSegmentation(A_ )
model.to(A_ )
model.eval()
UpperCamelCase = model(A_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) )
UpperCamelCase = model(A_ , labels=A_ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) )
def UpperCAmelCase_ ( self )-> int:
'''simple docstring'''
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs
UpperCamelCase = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_ , unittest.TestCase):
lowerCAmelCase_ = (
(BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
if is_torch_available()
else ()
)
lowerCAmelCase_ = (
{
"""feature-extraction""": BeitModel,
"""image-classification""": BeitForImageClassification,
"""image-segmentation""": BeitForSemanticSegmentation,
}
if is_torch_available()
else {}
)
lowerCAmelCase_ = False
lowerCAmelCase_ = False
lowerCAmelCase_ = False
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
UpperCamelCase = BeitModelTester(self )
UpperCamelCase = ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 )
def UpperCAmelCase_ ( self )-> Union[str, Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='BEiT does not use inputs_embeds' )
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
pass
@require_torch_multi_gpu
@unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' )
def UpperCAmelCase_ ( self )-> Optional[Any]:
'''simple docstring'''
pass
def UpperCAmelCase_ ( self )-> Tuple:
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(A_ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(A_ , nn.Linear ) )
def UpperCAmelCase_ ( self )-> List[Any]:
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(A_ )
UpperCamelCase = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase = [*signature.parameters.keys()]
UpperCamelCase = ['pixel_values']
self.assertListEqual(arg_names[:1] , A_ )
def UpperCAmelCase_ ( self )-> Union[str, Any]:
'''simple docstring'''
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A_ )
def UpperCAmelCase_ ( self )-> List[Any]:
'''simple docstring'''
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*A_ )
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*A_ )
def UpperCAmelCase_ ( self )-> List[str]:
'''simple docstring'''
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*A_ )
def UpperCAmelCase_ ( self )-> int:
'''simple docstring'''
if not self.model_tester.is_training:
return
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase = True
for model_class in self.all_model_classes:
# we don't test BeitForMaskedImageModeling
if model_class in [*get_values(A_ ), BeitForMaskedImageModeling]:
continue
UpperCamelCase = model_class(A_ )
model.to(A_ )
model.train()
UpperCamelCase = self._prepare_for_class(A_ , A_ , return_labels=A_ )
UpperCamelCase = model(**A_ ).loss
loss.backward()
def UpperCAmelCase_ ( self )-> List[str]:
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
if not self.model_tester.is_training:
return
UpperCamelCase = False
UpperCamelCase = True
for model_class in self.all_model_classes:
# we don't test BeitForMaskedImageModeling
if (
model_class in [*get_values(A_ ), BeitForMaskedImageModeling]
or not model_class.supports_gradient_checkpointing
):
continue
UpperCamelCase = model_class(A_ )
model.gradient_checkpointing_enable()
model.to(A_ )
model.train()
UpperCamelCase = self._prepare_for_class(A_ , A_ , return_labels=A_ )
UpperCamelCase = model(**A_ ).loss
loss.backward()
def UpperCAmelCase_ ( self )-> Union[str, Any]:
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
UpperCamelCase = _config_zero_init(A_ )
for model_class in self.all_model_classes:
UpperCamelCase = model_class(config=A_ )
for name, param in model.named_parameters():
# we skip lambda parameters as these require special initial values
# determined by config.layer_scale_init_value
if "lambda" in name:
continue
if param.requires_grad:
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , )
@slow
def UpperCAmelCase_ ( self )-> Dict:
'''simple docstring'''
for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase = BeitModel.from_pretrained(A_ )
self.assertIsNotNone(A_ )
def A_( ):
UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
return image
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase):
@cached_property
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None
@slow
def UpperCAmelCase_ ( self )-> Optional[Any]:
'''simple docstring'''
UpperCamelCase = BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(A_ )
UpperCamelCase = self.default_image_processor
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).pixel_values.to(A_ )
# prepare bool_masked_pos
UpperCamelCase = torch.ones((1, 196) , dtype=torch.bool ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(pixel_values=A_ , bool_masked_pos=A_ )
UpperCamelCase = outputs.logits
# verify the logits
UpperCamelCase = torch.Size((1, 196, 8192) )
self.assertEqual(logits.shape , A_ )
UpperCamelCase = torch.tensor(
[[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(A_ )
self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , A_ , atol=1e-2 ) )
@slow
def UpperCAmelCase_ ( self )-> Union[str, Any]:
'''simple docstring'''
UpperCamelCase = BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(A_ )
UpperCamelCase = self.default_image_processor
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits
# verify the logits
UpperCamelCase = torch.Size((1, 1000) )
self.assertEqual(logits.shape , A_ )
UpperCamelCase = torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(A_ )
self.assertTrue(torch.allclose(logits[0, :3] , A_ , atol=1e-4 ) )
UpperCamelCase = 281
self.assertEqual(logits.argmax(-1 ).item() , A_ )
@slow
def UpperCAmelCase_ ( self )-> Optional[Any]:
'''simple docstring'''
UpperCamelCase = BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to(
A_ )
UpperCamelCase = self.default_image_processor
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits
# verify the logits
UpperCamelCase = torch.Size((1, 21841) )
self.assertEqual(logits.shape , A_ )
UpperCamelCase = torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(A_ )
self.assertTrue(torch.allclose(logits[0, :3] , A_ , atol=1e-4 ) )
UpperCamelCase = 2396
self.assertEqual(logits.argmax(-1 ).item() , A_ )
@slow
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
UpperCamelCase = BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' )
UpperCamelCase = model.to(A_ )
UpperCamelCase = BeitImageProcessor(do_resize=A_ , size=640 , do_center_crop=A_ )
UpperCamelCase = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
UpperCamelCase = Image.open(ds[0]['file'] )
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits
# verify the logits
UpperCamelCase = torch.Size((1, 150, 160, 160) )
self.assertEqual(logits.shape , A_ )
UpperCamelCase = version.parse(PIL.__version__ ) < version.parse('9.0.0' )
if is_pillow_less_than_a:
UpperCamelCase = torch.tensor(
[
[[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]],
[[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]],
[[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]],
] , device=A_ , )
else:
UpperCamelCase = torch.tensor(
[
[[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]],
[[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]],
[[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]],
] , device=A_ , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , A_ , atol=1e-4 ) )
@slow
def UpperCAmelCase_ ( self )-> Tuple:
'''simple docstring'''
UpperCamelCase = BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' )
UpperCamelCase = model.to(A_ )
UpperCamelCase = BeitImageProcessor(do_resize=A_ , size=640 , do_center_crop=A_ )
UpperCamelCase = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
UpperCamelCase = Image.open(ds[0]['file'] )
UpperCamelCase = image_processor(images=A_ , return_tensors='pt' ).to(A_ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**A_ )
UpperCamelCase = outputs.logits.detach().cpu()
UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=A_ , target_sizes=[(500, 300)] )
UpperCamelCase = torch.Size((500, 300) )
self.assertEqual(segmentation[0].shape , A_ )
UpperCamelCase = image_processor.post_process_semantic_segmentation(outputs=A_ )
UpperCamelCase = torch.Size((160, 160) )
self.assertEqual(segmentation[0].shape , A_ )
| 3 | 1 |
'''simple docstring'''
import cmath
import math
def UpperCamelCase_ ( A__ : float , A__ : float , A__ : float , A__ : float ):
'''simple docstring'''
lowerCAmelCase_ : List[str] = math.radians(A__ )
lowerCAmelCase_ : Union[str, Any] = math.radians(A__ )
# Convert voltage and current to rectangular form
lowerCAmelCase_ : List[Any] = cmath.rect(A__ , A__ )
lowerCAmelCase_ : List[str] = cmath.rect(A__ , A__ )
# Calculate apparent power
return voltage_rect * current_rect
if __name__ == "__main__":
import doctest
doctest.testmod()
| 716 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
__A : Union[str, Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : Optional[Any] = ["FNetTokenizer"]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : List[str] = ["FNetTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : Optional[int] = [
"FNET_PRETRAINED_MODEL_ARCHIVE_LIST",
"FNetForMaskedLM",
"FNetForMultipleChoice",
"FNetForNextSentencePrediction",
"FNetForPreTraining",
"FNetForQuestionAnswering",
"FNetForSequenceClassification",
"FNetForTokenClassification",
"FNetLayer",
"FNetModel",
"FNetPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_fnet import FNetTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_fnet_fast import FNetTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_fnet import (
FNET_PRETRAINED_MODEL_ARCHIVE_LIST,
FNetForMaskedLM,
FNetForMultipleChoice,
FNetForNextSentencePrediction,
FNetForPreTraining,
FNetForQuestionAnswering,
FNetForSequenceClassification,
FNetForTokenClassification,
FNetLayer,
FNetModel,
FNetPreTrainedModel,
)
else:
import sys
__A : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 398 | 0 |
# Logistic Regression from scratch
# In[62]:
# In[63]:
# importing all the required libraries
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def a ( A__ ) -> List[Any]:
'''simple docstring'''
return 1 / (1 + np.exp(-z ))
def a ( A__ , A__ ) -> Any:
'''simple docstring'''
return (-y * np.log(A__ ) - (1 - y) * np.log(1 - h )).mean()
def a ( A__ , A__ , A__ ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : str = np.dot(A__ , A__ )
return np.sum(y * scores - np.log(1 + np.exp(A__ ) ) )
def a ( A__ , A__ , A__ , A__=7_0_0_0_0 ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : int = np.zeros(x.shape[1] )
for iterations in range(A__ ):
SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(A__ , A__ )
SCREAMING_SNAKE_CASE__ : Dict = sigmoid_function(A__ )
SCREAMING_SNAKE_CASE__ : int = np.dot(x.T , h - y ) / y.size
SCREAMING_SNAKE_CASE__ : Union[str, Any] = theta - alpha * gradient # updating the weights
SCREAMING_SNAKE_CASE__ : Optional[int] = np.dot(A__ , A__ )
SCREAMING_SNAKE_CASE__ : int = sigmoid_function(A__ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = cost_function(A__ , A__ )
if iterations % 1_0_0 == 0:
print(f"""loss: {j} \t""" ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
a_ :str = datasets.load_iris()
a_ :Dict = iris.data[:, :2]
a_ :int = (iris.target != 0) * 1
a_ :Dict = 0.1
a_ :str = logistic_reg(alpha, x, y, max_iterations=7_00_00)
print('theta: ', theta) # printing the theta i.e our weights vector
def a ( A__ ) -> int:
'''simple docstring'''
return sigmoid_function(
np.dot(A__ , A__ ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='b', label='0')
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='r', label='1')
((a_) , (a_)) :str = (x[:, 0].min(), x[:, 0].max())
((a_) , (a_)) :Tuple = (x[:, 1].min(), x[:, 1].max())
((a_) , (a_)) :Dict = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
a_ :Optional[int] = np.c_[xxa.ravel(), xxa.ravel()]
a_ :Optional[int] = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='black')
plt.legend()
plt.show()
| 35 |
'''simple docstring'''
import inspect
import unittest
from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class _UpperCamelCase ( _A ):
'''simple docstring'''
def lowercase__ ( self ):
"""simple docstring"""
a__ = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(_a , 'hidden_sizes' ) )
self.parent.assertTrue(hasattr(_a , 'neck_hidden_sizes' ) )
self.parent.assertTrue(hasattr(_a , 'num_attention_heads' ) )
class _UpperCamelCase :
'''simple docstring'''
def __init__( self , _a , _a=13 , _a=32 , _a=2 , _a=3 , _a=640 , _a=4 , _a="silu" , _a=3 , _a=32 , _a=0.1 , _a=0.1 , _a=0.1 , _a=0.02 , _a=True , _a=True , _a=10 , _a=None , ):
"""simple docstring"""
a__ = parent
a__ = batch_size
a__ = image_size
a__ = patch_size
a__ = num_channels
a__ = last_hidden_size
a__ = num_attention_heads
a__ = hidden_act
a__ = conv_kernel_size
a__ = output_stride
a__ = hidden_dropout_prob
a__ = attention_probs_dropout_prob
a__ = classifier_dropout_prob
a__ = use_labels
a__ = is_training
a__ = num_labels
a__ = initializer_range
a__ = scope
def lowercase__ ( self ):
"""simple docstring"""
a__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
a__ = None
a__ = None
if self.use_labels:
a__ = ids_tensor([self.batch_size] , self.num_labels )
a__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
a__ = self.get_config()
return config, pixel_values, labels, pixel_labels
def lowercase__ ( self ):
"""simple docstring"""
return MobileViTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , )
def lowercase__ ( self , _a , _a , _a , _a ):
"""simple docstring"""
a__ = MobileViTModel(config=_a )
model.to(_a )
model.eval()
a__ = model(_a )
self.parent.assertEqual(
result.last_hidden_state.shape , (
self.batch_size,
self.last_hidden_size,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def lowercase__ ( self , _a , _a , _a , _a ):
"""simple docstring"""
a__ = self.num_labels
a__ = MobileViTForImageClassification(_a )
model.to(_a )
model.eval()
a__ = model(_a , labels=_a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowercase__ ( self , _a , _a , _a , _a ):
"""simple docstring"""
a__ = self.num_labels
a__ = MobileViTForSemanticSegmentation(_a )
model.to(_a )
model.eval()
a__ = model(_a )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
a__ = model(_a , labels=_a )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def lowercase__ ( self ):
"""simple docstring"""
a__ = self.prepare_config_and_inputs()
a__ , a__ , a__ , a__ = config_and_inputs
a__ = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class _UpperCamelCase ( _A , _A , unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE:Optional[Any] = (
(MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
if is_torch_available()
else ()
)
SCREAMING_SNAKE_CASE:List[Any] = (
{
'feature-extraction': MobileViTModel,
'image-classification': MobileViTForImageClassification,
'image-segmentation': MobileViTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
SCREAMING_SNAKE_CASE:List[Any] = False
SCREAMING_SNAKE_CASE:Optional[Any] = False
SCREAMING_SNAKE_CASE:Union[str, Any] = False
SCREAMING_SNAKE_CASE:str = False
def lowercase__ ( self ):
"""simple docstring"""
a__ = MobileViTModelTester(self )
a__ = MobileViTConfigTester(self , config_class=_a , has_text_modality=_a )
def lowercase__ ( self ):
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='MobileViT does not use inputs_embeds' )
def lowercase__ ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='MobileViT does not support input and output embeddings' )
def lowercase__ ( self ):
"""simple docstring"""
pass
@unittest.skip(reason='MobileViT does not output attentions' )
def lowercase__ ( self ):
"""simple docstring"""
pass
def lowercase__ ( self ):
"""simple docstring"""
a__ , a__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a__ = model_class(_a )
a__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a__ = [*signature.parameters.keys()]
a__ = ['pixel_values']
self.assertListEqual(arg_names[:1] , _a )
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def lowercase__ ( self ):
"""simple docstring"""
pass
def lowercase__ ( self ):
"""simple docstring"""
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_a )
def lowercase__ ( self ):
"""simple docstring"""
def check_hidden_states_output(_a , _a , _a ):
a__ = model_class(_a )
model.to(_a )
model.eval()
with torch.no_grad():
a__ = model(**self._prepare_for_class(_a , _a ) )
a__ = outputs.hidden_states
a__ = 5
self.assertEqual(len(_a ) , _a )
# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
a__ = 2
for i in range(len(_a ) ):
self.assertListEqual(
list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , )
divisor *= 2
self.assertEqual(self.model_tester.output_stride , divisor // 2 )
a__ , a__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a__ = True
check_hidden_states_output(_a , _a , _a )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
a__ = True
check_hidden_states_output(_a , _a , _a )
def lowercase__ ( self ):
"""simple docstring"""
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_a )
def lowercase__ ( self ):
"""simple docstring"""
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*_a )
@slow
def lowercase__ ( self ):
"""simple docstring"""
for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
a__ = MobileViTModel.from_pretrained(_a )
self.assertIsNotNone(_a )
def lowerCAmelCase_ ( ):
a__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class _UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def lowercase__ ( self ):
"""simple docstring"""
return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small' ) if is_vision_available() else None
@slow
def lowercase__ ( self ):
"""simple docstring"""
a__ = MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(_a )
a__ = self.default_image_processor
a__ = prepare_img()
a__ = image_processor(images=_a , return_tensors='pt' ).to(_a )
# forward pass
with torch.no_grad():
a__ = model(**_a )
# verify the logits
a__ = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , _a )
a__ = torch.tensor([-1.9364, -1.2327, -0.4653] ).to(_a )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
@slow
def lowercase__ ( self ):
"""simple docstring"""
a__ = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
a__ = model.to(_a )
a__ = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
a__ = prepare_img()
a__ = image_processor(images=_a , return_tensors='pt' ).to(_a )
# forward pass
with torch.no_grad():
a__ = model(**_a )
a__ = outputs.logits
# verify the logits
a__ = torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , _a )
a__ = torch.tensor(
[
[[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
[[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
[[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
] , device=_a , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1e-4 ) )
@slow
def lowercase__ ( self ):
"""simple docstring"""
a__ = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
a__ = model.to(_a )
a__ = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
a__ = prepare_img()
a__ = image_processor(images=_a , return_tensors='pt' ).to(_a )
# forward pass
with torch.no_grad():
a__ = model(**_a )
a__ = outputs.logits.detach().cpu()
a__ = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(50, 60)] )
a__ = torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , _a )
a__ = image_processor.post_process_semantic_segmentation(outputs=_a )
a__ = torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , _a )
| 394 | 0 |
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_UpperCAmelCase = logging.get_logger(__name__)
class snake_case_ ( __lowerCamelCase ):
A_ = 'encoder-decoder'
A_ = True
def __init__( self : Tuple , **_snake_case : Tuple )->Optional[Any]:
'''simple docstring'''
super().__init__(**UpperCAmelCase_ )
assert (
"encoder" in kwargs and "decoder" in kwargs
), "Config has to be initialized with encoder and decoder config"
__lowerCAmelCase : List[str] = kwargs.pop("""encoder""" )
__lowerCAmelCase : Any = encoder_config.pop("""model_type""" )
__lowerCAmelCase : Optional[int] = kwargs.pop("""decoder""" )
__lowerCAmelCase : Union[str, Any] = decoder_config.pop("""model_type""" )
from ..auto.configuration_auto import AutoConfig
__lowerCAmelCase : Dict = AutoConfig.for_model(UpperCAmelCase_ , **UpperCAmelCase_ )
__lowerCAmelCase : List[Any] = AutoConfig.for_model(UpperCAmelCase_ , **UpperCAmelCase_ )
__lowerCAmelCase : Union[str, Any] = True
@classmethod
def UpperCAmelCase__ ( cls : Any , _snake_case : PretrainedConfig , _snake_case : PretrainedConfig , **_snake_case : Optional[int] )->List[Any]:
'''simple docstring'''
logger.info("""Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" )
__lowerCAmelCase : Dict = True
__lowerCAmelCase : Dict = True
return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **UpperCAmelCase_ )
def UpperCAmelCase__ ( self : Optional[Any] )->List[Any]:
'''simple docstring'''
__lowerCAmelCase : str = copy.deepcopy(self.__dict__ )
__lowerCAmelCase : Union[str, Any] = self.encoder.to_dict()
__lowerCAmelCase : Optional[int] = self.decoder.to_dict()
__lowerCAmelCase : Optional[int] = self.__class__.model_type
return output | 706 |
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/
import gc
import random
import tempfile
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
ControlNetModel,
DDIMScheduler,
StableDiffusionControlNetImgaImgPipeline,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import (
IMAGE_TO_IMAGE_IMAGE_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import (
PipelineKarrasSchedulerTesterMixin,
PipelineLatentTesterMixin,
PipelineTesterMixin,
)
enable_full_determinism()
class snake_case_ ( __lowercase ,__lowercase ,__lowercase ,unittest.TestCase ):
A_ = StableDiffusionControlNetImgaImgPipeline
A_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
A_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
A_ = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'control_image'} )
A_ = IMAGE_TO_IMAGE_IMAGE_PARAMS
def UpperCAmelCase__ ( self : Dict )->str:
'''simple docstring'''
torch.manual_seed(0 )
__lowerCAmelCase : List[Any] = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , )
torch.manual_seed(0 )
__lowerCAmelCase : Any = ControlNetModel(
block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , )
torch.manual_seed(0 )
__lowerCAmelCase : List[Any] = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_snake_case , set_alpha_to_one=_snake_case , )
torch.manual_seed(0 )
__lowerCAmelCase : int = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , )
torch.manual_seed(0 )
__lowerCAmelCase : List[str] = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )
__lowerCAmelCase : List[Any] = CLIPTextModel(_snake_case )
__lowerCAmelCase : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
__lowerCAmelCase : Tuple = {
"""unet""": unet,
"""controlnet""": controlnet,
"""scheduler""": scheduler,
"""vae""": vae,
"""text_encoder""": text_encoder,
"""tokenizer""": tokenizer,
"""safety_checker""": None,
"""feature_extractor""": None,
}
return components
def UpperCAmelCase__ ( self : int , _snake_case : str , _snake_case : int=0 )->str:
'''simple docstring'''
if str(_snake_case ).startswith("""mps""" ):
__lowerCAmelCase : int = torch.manual_seed(_snake_case )
else:
__lowerCAmelCase : Optional[int] = torch.Generator(device=_snake_case ).manual_seed(_snake_case )
__lowerCAmelCase : List[str] = 2
__lowerCAmelCase : Any = randn_tensor(
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=_snake_case , device=torch.device(_snake_case ) , )
__lowerCAmelCase : Any = floats_tensor(control_image.shape , rng=random.Random(_snake_case ) ).to(_snake_case )
__lowerCAmelCase : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__lowerCAmelCase : Tuple = Image.fromarray(np.uinta(_snake_case ) ).convert("""RGB""" ).resize((64, 64) )
__lowerCAmelCase : List[Any] = {
"""prompt""": """A painting of a squirrel eating a burger""",
"""generator""": generator,
"""num_inference_steps""": 2,
"""guidance_scale""": 6.0,
"""output_type""": """numpy""",
"""image""": image,
"""control_image""": control_image,
}
return inputs
def UpperCAmelCase__ ( self : Any )->Tuple:
'''simple docstring'''
return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 )
@unittest.skipIf(
torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , )
def UpperCAmelCase__ ( self : Dict )->int:
'''simple docstring'''
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 )
def UpperCAmelCase__ ( self : Optional[int] )->List[Any]:
'''simple docstring'''
self._test_inference_batch_single_identical(expected_max_diff=2E-3 )
class snake_case_ ( __lowercase ,__lowercase ,unittest.TestCase ):
A_ = StableDiffusionControlNetImgaImgPipeline
A_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
A_ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
A_ = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
def UpperCAmelCase__ ( self : Tuple )->Optional[int]:
'''simple docstring'''
torch.manual_seed(0 )
__lowerCAmelCase : Optional[int] = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , )
torch.manual_seed(0 )
def init_weights(_snake_case : Optional[Any] ):
if isinstance(_snake_case , torch.nn.Convad ):
torch.nn.init.normal(m.weight )
m.bias.data.fill_(1.0 )
__lowerCAmelCase : Dict = ControlNetModel(
block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , )
controlneta.controlnet_down_blocks.apply(_snake_case )
torch.manual_seed(0 )
__lowerCAmelCase : Optional[Any] = ControlNetModel(
block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , )
controlneta.controlnet_down_blocks.apply(_snake_case )
torch.manual_seed(0 )
__lowerCAmelCase : Optional[Any] = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=_snake_case , set_alpha_to_one=_snake_case , )
torch.manual_seed(0 )
__lowerCAmelCase : List[str] = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , )
torch.manual_seed(0 )
__lowerCAmelCase : Any = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )
__lowerCAmelCase : Optional[Any] = CLIPTextModel(_snake_case )
__lowerCAmelCase : Optional[int] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
__lowerCAmelCase : List[Any] = MultiControlNetModel([controlneta, controlneta] )
__lowerCAmelCase : List[str] = {
"""unet""": unet,
"""controlnet""": controlnet,
"""scheduler""": scheduler,
"""vae""": vae,
"""text_encoder""": text_encoder,
"""tokenizer""": tokenizer,
"""safety_checker""": None,
"""feature_extractor""": None,
}
return components
def UpperCAmelCase__ ( self : List[Any] , _snake_case : Dict , _snake_case : List[Any]=0 )->int:
'''simple docstring'''
if str(_snake_case ).startswith("""mps""" ):
__lowerCAmelCase : int = torch.manual_seed(_snake_case )
else:
__lowerCAmelCase : Optional[int] = torch.Generator(device=_snake_case ).manual_seed(_snake_case )
__lowerCAmelCase : Union[str, Any] = 2
__lowerCAmelCase : Optional[int] = [
randn_tensor(
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=_snake_case , device=torch.device(_snake_case ) , ),
randn_tensor(
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=_snake_case , device=torch.device(_snake_case ) , ),
]
__lowerCAmelCase : int = floats_tensor(control_image[0].shape , rng=random.Random(_snake_case ) ).to(_snake_case )
__lowerCAmelCase : List[str] = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__lowerCAmelCase : Optional[int] = Image.fromarray(np.uinta(_snake_case ) ).convert("""RGB""" ).resize((64, 64) )
__lowerCAmelCase : Union[str, Any] = {
"""prompt""": """A painting of a squirrel eating a burger""",
"""generator""": generator,
"""num_inference_steps""": 2,
"""guidance_scale""": 6.0,
"""output_type""": """numpy""",
"""image""": image,
"""control_image""": control_image,
}
return inputs
def UpperCAmelCase__ ( self : Optional[int] )->str:
'''simple docstring'''
__lowerCAmelCase : int = self.get_dummy_components()
__lowerCAmelCase : Optional[int] = self.pipeline_class(**_snake_case )
pipe.to(_snake_case )
__lowerCAmelCase : Any = 10.0
__lowerCAmelCase : Tuple = 4
__lowerCAmelCase : List[Any] = self.get_dummy_inputs(_snake_case )
__lowerCAmelCase : int = steps
__lowerCAmelCase : Tuple = scale
__lowerCAmelCase : Optional[int] = pipe(**_snake_case )[0]
__lowerCAmelCase : str = self.get_dummy_inputs(_snake_case )
__lowerCAmelCase : List[Any] = steps
__lowerCAmelCase : Optional[Any] = scale
__lowerCAmelCase : Any = pipe(**_snake_case , control_guidance_start=0.1 , control_guidance_end=0.2 )[0]
__lowerCAmelCase : str = self.get_dummy_inputs(_snake_case )
__lowerCAmelCase : Optional[Any] = steps
__lowerCAmelCase : str = scale
__lowerCAmelCase : str = pipe(**_snake_case , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0]
__lowerCAmelCase : Tuple = self.get_dummy_inputs(_snake_case )
__lowerCAmelCase : Optional[int] = steps
__lowerCAmelCase : Union[str, Any] = scale
__lowerCAmelCase : List[Any] = pipe(**_snake_case , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0]
# make sure that all outputs are different
assert np.sum(np.abs(output_a - output_a ) ) > 1E-3
assert np.sum(np.abs(output_a - output_a ) ) > 1E-3
assert np.sum(np.abs(output_a - output_a ) ) > 1E-3
def UpperCAmelCase__ ( self : Tuple )->Dict:
'''simple docstring'''
return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 )
@unittest.skipIf(
torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , )
def UpperCAmelCase__ ( self : Tuple )->int:
'''simple docstring'''
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 )
def UpperCAmelCase__ ( self : Union[str, Any] )->List[str]:
'''simple docstring'''
self._test_inference_batch_single_identical(expected_max_diff=2E-3 )
def UpperCAmelCase__ ( self : str )->Tuple:
'''simple docstring'''
__lowerCAmelCase : Dict = self.get_dummy_components()
__lowerCAmelCase : Optional[int] = self.pipeline_class(**_snake_case )
pipe.to(_snake_case )
pipe.set_progress_bar_config(disable=_snake_case )
with tempfile.TemporaryDirectory() as tmpdir:
try:
# save_pretrained is not implemented for Multi-ControlNet
pipe.save_pretrained(_snake_case )
except NotImplementedError:
pass
@slow
@require_torch_gpu
class snake_case_ ( unittest.TestCase ):
def UpperCAmelCase__ ( self : Union[str, Any] )->Any:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase__ ( self : Union[str, Any] )->Dict:
'''simple docstring'''
__lowerCAmelCase : str = ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" )
__lowerCAmelCase : List[Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained(
"""runwayml/stable-diffusion-v1-5""" , safety_checker=_snake_case , controlnet=_snake_case )
pipe.enable_model_cpu_offload()
pipe.set_progress_bar_config(disable=_snake_case )
__lowerCAmelCase : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 )
__lowerCAmelCase : List[str] = """evil space-punk bird"""
__lowerCAmelCase : Tuple = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((512, 512) )
__lowerCAmelCase : List[Any] = load_image(
"""https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((512, 512) )
__lowerCAmelCase : int = pipe(
_snake_case , _snake_case , control_image=_snake_case , generator=_snake_case , output_type="""np""" , num_inference_steps=50 , strength=0.6 , )
__lowerCAmelCase : Optional[Any] = output.images[0]
assert image.shape == (512, 512, 3)
__lowerCAmelCase : Dict = load_numpy(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" )
assert np.abs(expected_image - image ).max() < 9E-2 | 240 | 0 |
'''simple docstring'''
import fire
from utils import calculate_rouge, save_json
def UpperCamelCase_( snake_case : List[Any] , snake_case : Dict , snake_case : Optional[int]=None , **snake_case : List[Any] ):
'''simple docstring'''
snake_case_ = [x.strip() for x in open(snake_case ).readlines()]
snake_case_ = [x.strip() for x in open(snake_case ).readlines()][: len(snake_case )]
snake_case_ = calculate_rouge(snake_case , snake_case , **snake_case )
if save_path is not None:
save_json(snake_case , snake_case , indent=snake_case )
return metrics # these print nicely
if __name__ == "__main__":
fire.Fire(calculate_rouge_path)
| 400 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_SCREAMING_SNAKE_CASE : List[Any] = {
"configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"],
"convert_funnel_original_tf_checkpoint_to_pytorch": [],
"tokenization_funnel": ["FunnelTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE : Optional[int] = ["FunnelTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE : List[Any] = [
"FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST",
"FunnelBaseModel",
"FunnelForMaskedLM",
"FunnelForMultipleChoice",
"FunnelForPreTraining",
"FunnelForQuestionAnswering",
"FunnelForSequenceClassification",
"FunnelForTokenClassification",
"FunnelModel",
"FunnelPreTrainedModel",
"load_tf_weights_in_funnel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE : Dict = [
"TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFFunnelBaseModel",
"TFFunnelForMaskedLM",
"TFFunnelForMultipleChoice",
"TFFunnelForPreTraining",
"TFFunnelForQuestionAnswering",
"TFFunnelForSequenceClassification",
"TFFunnelForTokenClassification",
"TFFunnelModel",
"TFFunnelPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig
from .tokenization_funnel import FunnelTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_funnel_fast import FunnelTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_funnel import (
FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
FunnelBaseModel,
FunnelForMaskedLM,
FunnelForMultipleChoice,
FunnelForPreTraining,
FunnelForQuestionAnswering,
FunnelForSequenceClassification,
FunnelForTokenClassification,
FunnelModel,
FunnelPreTrainedModel,
load_tf_weights_in_funnel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_funnel import (
TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFFunnelBaseModel,
TFFunnelForMaskedLM,
TFFunnelForMultipleChoice,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForSequenceClassification,
TFFunnelForTokenClassification,
TFFunnelModel,
TFFunnelPreTrainedModel,
)
else:
import sys
_SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 400 | 1 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel
@require_tf
class A_:
"""simple docstring"""
a_ : Dict = PegasusConfig
a_ : Optional[Any] = {}
a_ : Optional[Any] = """gelu"""
def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=40 , A=2 , A=1 , A=0 , ):
_lowerCamelCase : Dict = parent
_lowerCamelCase : Any = batch_size
_lowerCamelCase : Dict = seq_length
_lowerCamelCase : List[str] = is_training
_lowerCamelCase : List[str] = use_labels
_lowerCamelCase : Union[str, Any] = vocab_size
_lowerCamelCase : Optional[Any] = hidden_size
_lowerCamelCase : List[str] = num_hidden_layers
_lowerCamelCase : int = num_attention_heads
_lowerCamelCase : Union[str, Any] = intermediate_size
_lowerCamelCase : Dict = hidden_dropout_prob
_lowerCamelCase : Dict = attention_probs_dropout_prob
_lowerCamelCase : Dict = max_position_embeddings
_lowerCamelCase : str = eos_token_id
_lowerCamelCase : int = pad_token_id
_lowerCamelCase : Optional[int] = bos_token_id
def _lowerCAmelCase ( self ):
_lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
_lowerCamelCase : Dict = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
_lowerCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 )
_lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
_lowerCamelCase : Tuple = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
_lowerCamelCase : Tuple = prepare_pegasus_inputs_dict(A , A , A )
return config, inputs_dict
def _lowerCAmelCase ( self , A , A ):
_lowerCamelCase : Optional[Any] = TFPegasusModel(config=A ).get_decoder()
_lowerCamelCase : Tuple = inputs_dict['input_ids']
_lowerCamelCase : Optional[int] = input_ids[:1, :]
_lowerCamelCase : str = inputs_dict['attention_mask'][:1, :]
_lowerCamelCase : str = inputs_dict['head_mask']
_lowerCamelCase : Optional[int] = 1
# first forward pass
_lowerCamelCase : Dict = model(A , attention_mask=A , head_mask=A , use_cache=A )
_lowerCamelCase , _lowerCamelCase : Dict = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
_lowerCamelCase : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size )
_lowerCamelCase : Optional[int] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
_lowerCamelCase : Tuple = tf.concat([input_ids, next_tokens] , axis=-1 )
_lowerCamelCase : str = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
_lowerCamelCase : Tuple = model(A , attention_mask=A )[0]
_lowerCamelCase : str = model(A , attention_mask=A , past_key_values=A )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
_lowerCamelCase : int = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
_lowerCamelCase : List[Any] = output_from_no_past[:, -3:, random_slice_idx]
_lowerCamelCase : Tuple = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(A , A , rtol=1E-3 )
def UpperCAmelCase_ ( __a : Tuple , __a : int , __a : Tuple , __a : Optional[Any]=None , __a : int=None , __a : Any=None , __a : List[str]=None , __a : Union[str, Any]=None , ):
'''simple docstring'''
if attention_mask is None:
_lowerCamelCase : Tuple = tf.cast(tf.math.not_equal(__a , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
_lowerCamelCase : Optional[Any] = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
_lowerCamelCase : Union[str, Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_lowerCamelCase : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_lowerCamelCase : Union[str, Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class A_(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ):
"""simple docstring"""
a_ : Union[str, Any] = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
a_ : Optional[int] = (TFPegasusForConditionalGeneration,) if is_tf_available() else ()
a_ : int = (
{
"""conversational""": TFPegasusForConditionalGeneration,
"""feature-extraction""": TFPegasusModel,
"""summarization""": TFPegasusForConditionalGeneration,
"""text2text-generation""": TFPegasusForConditionalGeneration,
"""translation""": TFPegasusForConditionalGeneration,
}
if is_tf_available()
else {}
)
a_ : Dict = True
a_ : Any = False
a_ : int = False
def _lowerCAmelCase ( self ):
_lowerCamelCase : List[str] = TFPegasusModelTester(self )
_lowerCamelCase : int = ConfigTester(self , config_class=A )
def _lowerCAmelCase ( self ):
self.config_tester.run_common_tests()
def _lowerCAmelCase ( self ):
_lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*A )
@require_sentencepiece
@require_tokenizers
@require_tf
class A_(unittest.TestCase ):
"""simple docstring"""
a_ : Union[str, Any] = [
""" PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""",
""" The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """,
]
a_ : List[Any] = [
"""California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to"""
""" reduce the risk of wildfires.""",
"""N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.""",
] # differs slightly from pytorch, likely due to numerical differences in linear layers
a_ : Any = """google/pegasus-xsum"""
@cached_property
def _lowerCAmelCase ( self ):
return AutoTokenizer.from_pretrained(self.model_name )
@cached_property
def _lowerCAmelCase ( self ):
_lowerCamelCase : List[str] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
return model
def _lowerCAmelCase ( self , **A ):
_lowerCamelCase : Optional[int] = self.translate_src_text(**A )
assert self.expected_text == generated_words
def _lowerCAmelCase ( self , **A ):
_lowerCamelCase : Union[str, Any] = self.tokenizer(self.src_text , **A , padding=A , return_tensors='tf' )
_lowerCamelCase : Any = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=A , )
_lowerCamelCase : Optional[int] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=A )
return generated_words
@slow
def _lowerCAmelCase ( self ):
self._assert_generated_batch_equal_expected()
| 349 |
"""simple docstring"""
from argparse import ArgumentParser
from .add_new_model import AddNewModelCommand
from .add_new_model_like import AddNewModelLikeCommand
from .convert import ConvertCommand
from .download import DownloadCommand
from .env import EnvironmentCommand
from .lfs import LfsCommands
from .pt_to_tf import PTtoTFCommand
from .run import RunCommand
from .serving import ServeCommand
from .user import UserCommands
def UpperCAmelCase_ ( ):
'''simple docstring'''
_lowerCamelCase : int = ArgumentParser('Transformers CLI tool' , usage='transformers-cli <command> [<args>]' )
_lowerCamelCase : List[Any] = parser.add_subparsers(help='transformers-cli command helpers' )
# Register commands
ConvertCommand.register_subcommand(__a )
DownloadCommand.register_subcommand(__a )
EnvironmentCommand.register_subcommand(__a )
RunCommand.register_subcommand(__a )
ServeCommand.register_subcommand(__a )
UserCommands.register_subcommand(__a )
AddNewModelCommand.register_subcommand(__a )
AddNewModelLikeCommand.register_subcommand(__a )
LfsCommands.register_subcommand(__a )
PTtoTFCommand.register_subcommand(__a )
# Let's go
_lowerCamelCase : Any = parser.parse_args()
if not hasattr(__a , 'func' ):
parser.print_help()
exit(1 )
# Run
_lowerCamelCase : List[Any] = args.func(__a )
service.run()
if __name__ == "__main__":
main()
| 349 | 1 |
from __future__ import annotations
from typing import TypedDict
class SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ):
"""simple docstring"""
lowerCamelCase : str =42
lowerCamelCase : int =42
def snake_case_ (__A : str ) -> Tuple:
if not isinstance(__A , __A ):
raise TypeError("""The parameter s type must be str.""" )
return [s[i:] + s[:i] for i in range(len(__A ) )]
def snake_case_ (__A : str ) -> str:
if not isinstance(__A , __A ):
raise TypeError("""The parameter s type must be str.""" )
if not s:
raise ValueError("""The parameter s must not be empty.""" )
__lowerCAmelCase : Any = all_rotations(__A )
rotations.sort() # sort the list of rotations in alphabetically order
# make a string composed of the last char of each rotation
__lowerCAmelCase : BWTTransformDict = {
"bwt_string": "".join([word[-1] for word in rotations] ),
"idx_original_string": rotations.index(__A ),
}
return response
def snake_case_ (__A : str , __A : int ) -> str:
if not isinstance(__A , __A ):
raise TypeError("""The parameter bwt_string type must be str.""" )
if not bwt_string:
raise ValueError("""The parameter bwt_string must not be empty.""" )
try:
__lowerCAmelCase : List[Any] = int(__A )
except ValueError:
raise TypeError(
"""The parameter idx_original_string type must be int or passive"""
""" of cast to int.""" )
if idx_original_string < 0:
raise ValueError("""The parameter idx_original_string must not be lower than 0.""" )
if idx_original_string >= len(__A ):
raise ValueError(
"""The parameter idx_original_string must be lower than""" """ len(bwt_string).""" )
__lowerCAmelCase : Any = [""""""] * len(__A )
for _ in range(len(__A ) ):
for i in range(len(__A ) ):
__lowerCAmelCase : int = bwt_string[i] + ordered_rotations[i]
ordered_rotations.sort()
return ordered_rotations[idx_original_string]
if __name__ == "__main__":
__UpperCAmelCase = """Provide a string that I will generate its BWT transform: """
__UpperCAmelCase = input(entry_msg).strip()
__UpperCAmelCase = bwt_transform(s)
print(
F'Burrows Wheeler transform for string \'{s}\' results '
F'in \'{result["bwt_string"]}\''
)
__UpperCAmelCase = reverse_bwt(result["""bwt_string"""], result["""idx_original_string"""])
print(
F'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' '
F'we get original string \'{original_string}\''
)
| 651 |
'''simple docstring'''
import unittest
from transformers import (
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
TextaTextGenerationPipeline,
pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available
from .test_pipelines_common import ANY
if is_torch_available():
import torch
@is_pipeline_test
class __lowerCAmelCase ( unittest.TestCase ):
'''simple docstring'''
a_ = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
a_ = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
def _a ( self : List[str] ,_a : int ,_a : Any ,_a : int ):
'''simple docstring'''
A_ : Dict = TextaTextGenerationPipeline(model=_a ,tokenizer=_a )
return generator, ["Something to write", "Something else"]
def _a ( self : str ,_a : Union[str, Any] ,_a : int ):
'''simple docstring'''
A_ : Any = generator("""Something there""" )
self.assertEqual(_a ,[{"""generated_text""": ANY(_a )}] )
# These are encoder decoder, they don't just append to incoming string
self.assertFalse(outputs[0]["""generated_text"""].startswith("""Something there""" ) )
A_ : List[Any] = generator(["""This is great !""", """Something else"""] ,num_return_sequences=2 ,do_sample=_a )
self.assertEqual(
_a ,[
[{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}],
[{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}],
] ,)
A_ : List[str] = generator(
["""This is great !""", """Something else"""] ,num_return_sequences=2 ,batch_size=2 ,do_sample=_a )
self.assertEqual(
_a ,[
[{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}],
[{"""generated_text""": ANY(_a )}, {"""generated_text""": ANY(_a )}],
] ,)
with self.assertRaises(_a ):
generator(4 )
@require_torch
def _a ( self : Union[str, Any] ):
'''simple docstring'''
A_ : int = pipeline("""text2text-generation""" ,model="""patrickvonplaten/t5-tiny-random""" ,framework="""pt""" )
# do_sample=False necessary for reproducibility
A_ : Tuple = generator("""Something there""" ,do_sample=_a )
self.assertEqual(_a ,[{"""generated_text""": """"""}] )
A_ : Optional[int] = 3
A_ : Tuple = generator(
"""Something there""" ,num_return_sequences=_a ,num_beams=_a ,)
A_ : Optional[Any] = [
{"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide Beide"""},
{"""generated_text""": """Beide Beide Beide Beide Beide Beide Beide Beide"""},
{"""generated_text""": """"""},
]
self.assertEqual(_a ,_a )
A_ : Optional[int] = generator("""This is a test""" ,do_sample=_a ,num_return_sequences=2 ,return_tensors=_a )
self.assertEqual(
_a ,[
{"""generated_token_ids""": ANY(torch.Tensor )},
{"""generated_token_ids""": ANY(torch.Tensor )},
] ,)
A_ : Dict = generator.model.config.eos_token_id
A_ : Optional[int] = """<pad>"""
A_ : List[Any] = generator(
["""This is a test""", """This is a second test"""] ,do_sample=_a ,num_return_sequences=2 ,batch_size=2 ,return_tensors=_a ,)
self.assertEqual(
_a ,[
[
{"""generated_token_ids""": ANY(torch.Tensor )},
{"""generated_token_ids""": ANY(torch.Tensor )},
],
[
{"""generated_token_ids""": ANY(torch.Tensor )},
{"""generated_token_ids""": ANY(torch.Tensor )},
],
] ,)
@require_tf
def _a ( self : List[Any] ):
'''simple docstring'''
A_ : Optional[int] = pipeline("""text2text-generation""" ,model="""patrickvonplaten/t5-tiny-random""" ,framework="""tf""" )
# do_sample=False necessary for reproducibility
A_ : Dict = generator("""Something there""" ,do_sample=_a )
self.assertEqual(_a ,[{"""generated_text""": """"""}] )
| 665 | 0 |
'''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 : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name
def _lowerCAmelCase ( __a ) -> int:
'''simple docstring'''
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 ):
_UpperCamelCase :List[str] =[image]
if isinstance(image[0] , PIL.Image.Image ):
_UpperCamelCase , _UpperCamelCase :int =image[0].size
_UpperCamelCase , _UpperCamelCase :str =(x - x % 8 for x in (w, h)) # resize to integer multiple of 8
_UpperCamelCase :Any =[np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image]
_UpperCamelCase :int =np.concatenate(__a , axis=0 )
_UpperCamelCase :Optional[Any] =np.array(__a ).astype(np.floataa ) / 2_55.0
_UpperCamelCase :Dict =image.transpose(0 , 3 , 1 , 2 )
_UpperCamelCase :Any =2.0 * image - 1.0
_UpperCamelCase :Any =torch.from_numpy(__a )
elif isinstance(image[0] , torch.Tensor ):
_UpperCamelCase :List[Any] =torch.cat(__a , dim=0 )
return image
def _lowerCAmelCase ( __a ) -> Any:
'''simple docstring'''
if isinstance(__a , torch.Tensor ):
return mask
elif isinstance(__a , PIL.Image.Image ):
_UpperCamelCase :Optional[Any] =[mask]
if isinstance(mask[0] , PIL.Image.Image ):
_UpperCamelCase , _UpperCamelCase :str =mask[0].size
_UpperCamelCase , _UpperCamelCase :str =(x - x % 32 for x in (w, h)) # resize to integer multiple of 32
_UpperCamelCase :Dict =[np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask]
_UpperCamelCase :List[Any] =np.concatenate(__a , axis=0 )
_UpperCamelCase :List[str] =mask.astype(np.floataa ) / 2_55.0
_UpperCamelCase :Optional[int] =0
_UpperCamelCase :Tuple =1
_UpperCamelCase :Union[str, Any] =torch.from_numpy(__a )
elif isinstance(mask[0] , torch.Tensor ):
_UpperCamelCase :Any =torch.cat(__a , dim=0 )
return mask
class lowerCamelCase__ ( __lowerCamelCase ):
__UpperCAmelCase = 42
__UpperCAmelCase = 42
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> str:
"""simple docstring"""
super().__init__()
self.register_modules(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ )
@torch.no_grad()
def __call__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 250 , lowerCAmelCase__ = 0.0 , lowerCAmelCase__ = 10 , lowerCAmelCase__ = 10 , lowerCAmelCase__ = None , lowerCAmelCase__ = "pil" , lowerCAmelCase__ = True , ) -> Any:
"""simple docstring"""
_UpperCamelCase :int =image
_UpperCamelCase :Optional[Any] =_preprocess_image(SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :Optional[int] =original_image.to(device=self.device , dtype=self.unet.dtype )
_UpperCamelCase :str =_preprocess_mask(SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :List[str] =mask_image.to(device=self.device , dtype=self.unet.dtype )
_UpperCamelCase :Dict =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.''' )
_UpperCamelCase :Any =original_image.shape
_UpperCamelCase :Dict =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 )
_UpperCamelCase :str =eta
_UpperCamelCase :Optional[Any] =self.scheduler.timesteps[0] + 1
_UpperCamelCase :Dict =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
_UpperCamelCase :Tuple =self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample
# compute previous image: x_t -> x_t-1
_UpperCamelCase :List[Any] =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
_UpperCamelCase :Optional[Any] =self.scheduler.undo_step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :str =t
_UpperCamelCase :List[str] =(image / 2 + 0.5).clamp(0 , 1 )
_UpperCamelCase :Any =image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
_UpperCamelCase :List[Any] =self.numpy_to_pil(SCREAMING_SNAKE_CASE_ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ ) | 720 | '''simple docstring'''
import numpy as np
import skfuzzy as fuzz
if __name__ == "__main__":
# Create universe of discourse in Python using linspace ()
_lowerCamelCase : Optional[int] = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False)
# Create two fuzzy sets by defining any membership function
# (trapmf(), gbellmf(), gaussmf(), etc).
_lowerCamelCase : List[Any] = [0, 25, 50]
_lowerCamelCase : Dict = [25, 50, 75]
_lowerCamelCase : Optional[Any] = fuzz.membership.trimf(X, abca)
_lowerCamelCase : Any = fuzz.membership.trimf(X, abca)
# Compute the different operations using inbuilt functions.
_lowerCamelCase : Optional[Any] = np.ones(75)
_lowerCamelCase : Optional[int] = np.zeros((75,))
# 1. Union = max(µA(x), µB(x))
_lowerCamelCase : int = fuzz.fuzzy_or(X, young, X, middle_aged)[1]
# 2. Intersection = min(µA(x), µB(x))
_lowerCamelCase : Tuple = fuzz.fuzzy_and(X, young, X, middle_aged)[1]
# 3. Complement (A) = (1- min(µA(x))
_lowerCamelCase : List[str] = fuzz.fuzzy_not(young)
# 4. Difference (A/B) = min(µA(x),(1- µB(x)))
_lowerCamelCase : Any = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1]
# 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))]
_lowerCamelCase : Tuple = young + middle_aged - (young * middle_aged)
# 6. Algebraic Product = (µA(x) * µB(x))
_lowerCamelCase : int = young * middle_aged
# 7. Bounded Sum = min[1,(µA(x), µB(x))]
_lowerCamelCase : str = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1]
# 8. Bounded difference = min[0,(µA(x), µB(x))]
_lowerCamelCase : Dict = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1]
# max-min composition
# max-product composition
# Plot each set A, set B and each operation result using plot() and subplot().
from matplotlib import pyplot as plt
plt.figure()
plt.subplot(4, 3, 1)
plt.plot(X, young)
plt.title("""Young""")
plt.grid(True)
plt.subplot(4, 3, 2)
plt.plot(X, middle_aged)
plt.title("""Middle aged""")
plt.grid(True)
plt.subplot(4, 3, 3)
plt.plot(X, union)
plt.title("""union""")
plt.grid(True)
plt.subplot(4, 3, 4)
plt.plot(X, intersection)
plt.title("""intersection""")
plt.grid(True)
plt.subplot(4, 3, 5)
plt.plot(X, complement_a)
plt.title("""complement_a""")
plt.grid(True)
plt.subplot(4, 3, 6)
plt.plot(X, difference)
plt.title("""difference a/b""")
plt.grid(True)
plt.subplot(4, 3, 7)
plt.plot(X, alg_sum)
plt.title("""alg_sum""")
plt.grid(True)
plt.subplot(4, 3, 8)
plt.plot(X, alg_product)
plt.title("""alg_product""")
plt.grid(True)
plt.subplot(4, 3, 9)
plt.plot(X, bdd_sum)
plt.title("""bdd_sum""")
plt.grid(True)
plt.subplot(4, 3, 10)
plt.plot(X, bdd_difference)
plt.title("""bdd_difference""")
plt.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.show() | 512 | 0 |
'''simple docstring'''
from .constants import (
MODEL_NAME,
OPTIMIZER_NAME,
RNG_STATE_NAME,
SAFE_WEIGHTS_INDEX_NAME,
SAFE_WEIGHTS_NAME,
SCALER_NAME,
SCHEDULER_NAME,
TORCH_LAUNCH_PARAMS,
WEIGHTS_INDEX_NAME,
WEIGHTS_NAME,
)
from .dataclasses import (
BnbQuantizationConfig,
ComputeEnvironment,
CustomDtype,
DeepSpeedPlugin,
DistributedDataParallelKwargs,
DistributedType,
DynamoBackend,
FPaRecipeKwargs,
FullyShardedDataParallelPlugin,
GradientAccumulationPlugin,
GradScalerKwargs,
InitProcessGroupKwargs,
KwargsHandler,
LoggerType,
MegatronLMPlugin,
PrecisionType,
ProjectConfiguration,
RNGType,
SageMakerDistributedType,
TensorInformation,
TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
get_ccl_version,
is_abit_bnb_available,
is_abit_bnb_available,
is_aim_available,
is_bfaa_available,
is_bnb_available,
is_botoa_available,
is_ccl_available,
is_comet_ml_available,
is_datasets_available,
is_deepspeed_available,
is_fpa_available,
is_ipex_available,
is_megatron_lm_available,
is_mlflow_available,
is_mps_available,
is_npu_available,
is_rich_available,
is_safetensors_available,
is_sagemaker_available,
is_tensorboard_available,
is_tpu_available,
is_transformers_available,
is_wandb_available,
is_xpu_available,
)
from .modeling import (
check_device_map,
check_tied_parameters_in_config,
check_tied_parameters_on_same_device,
compute_module_sizes,
convert_file_size_to_int,
dtype_byte_size,
find_tied_parameters,
get_balanced_memory,
get_max_layer_size,
get_max_memory,
get_mixed_precision_context_manager,
id_tensor_storage,
infer_auto_device_map,
load_checkpoint_in_model,
load_offloaded_weights,
load_state_dict,
named_module_tensors,
retie_parameters,
set_module_tensor_to_device,
shard_checkpoint,
)
from .offload import (
OffloadedWeightsLoader,
PrefixedDataset,
extract_submodules_state_dict,
load_offloaded_weight,
offload_state_dict,
offload_weight,
save_offload_index,
)
from .operations import (
broadcast,
broadcast_object_list,
concatenate,
convert_outputs_to_fpaa,
convert_to_fpaa,
find_batch_size,
find_device,
gather,
gather_object,
get_data_structure,
honor_type,
initialize_tensors,
is_namedtuple,
is_tensor_information,
is_torch_tensor,
listify,
pad_across_processes,
recursively_apply,
reduce,
send_to_device,
slice_tensors,
)
from .versions import compare_versions, is_torch_version
if is_deepspeed_available():
from .deepspeed import (
DeepSpeedEngineWrapper,
DeepSpeedOptimizerWrapper,
DeepSpeedSchedulerWrapper,
DummyOptim,
DummyScheduler,
HfDeepSpeedConfig,
)
from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
PrepareForLaunch,
_filter_args,
prepare_deepspeed_cmd_env,
prepare_multi_gpu_env,
prepare_sagemager_args_inputs,
prepare_simple_launcher_cmd_env,
prepare_tpu,
)
from .megatron_lm import (
AbstractTrainStep,
BertTrainStep,
GPTTrainStep,
MegatronEngine,
MegatronLMDummyDataLoader,
MegatronLMDummyScheduler,
MegatronLMOptimizerWrapper,
MegatronLMSchedulerWrapper,
TaTrainStep,
avg_losses_across_data_parallel_group,
gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
extract_model_from_parallel,
get_pretty_name,
is_port_in_use,
merge_dicts,
patch_environment,
save,
wait_for_everyone,
write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers
| 42 |
from typing import Any
import numpy as np
def __UpperCamelCase ( _lowerCAmelCase ) -> bool:
"""simple docstring"""
return np.array_equal(_lowerCAmelCase , matrix.conjugate().T )
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> Any:
"""simple docstring"""
A : Any = v.conjugate().T
A : List[Any] = v_star.dot(_lowerCAmelCase )
assert isinstance(_lowerCAmelCase , np.ndarray )
return (v_star_dot.dot(_lowerCAmelCase )) / (v_star.dot(_lowerCAmelCase ))
def __UpperCamelCase ( ) -> None:
"""simple docstring"""
A : Any = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] )
A : str = np.array([[1], [2], [3]] )
assert is_hermitian(_lowerCAmelCase ), f'''{a} is not hermitian.'''
print(rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) )
A : Tuple = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] )
assert is_hermitian(_lowerCAmelCase ), f'''{a} is not hermitian.'''
assert rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) == float(3 )
if __name__ == "__main__":
import doctest
doctest.testmod()
tests()
| 662 | 0 |
"""simple docstring"""
import torch
from torch import nn
from transformers import CLIPPreTrainedModel, CLIPVisionModel
from ...models.attention import BasicTransformerBlock
from ...utils import logging
SCREAMING_SNAKE_CASE__:str = logging.get_logger(__name__) # pylint: disable=invalid-name
class snake_case__ ( snake_case_ ):
def __init__( self , lowerCamelCase , lowerCamelCase=768 ):
super().__init__(lowerCamelCase )
__a = proj_size
__a = CLIPVisionModel(lowerCamelCase )
__a = PaintByExampleMapper(lowerCamelCase )
__a = nn.LayerNorm(config.hidden_size )
__a = nn.Linear(config.hidden_size , self.proj_size )
# uncondition for scaling
__a = nn.Parameter(torch.randn((1, 1, self.proj_size) ) )
def a__ ( self , lowerCamelCase , lowerCamelCase=False ):
__a = self.model(pixel_values=lowerCamelCase )
__a = clip_output.pooler_output
__a = self.mapper(latent_states[:, None] )
__a = self.final_layer_norm(lowerCamelCase )
__a = self.proj_out(lowerCamelCase )
if return_uncond_vector:
return latent_states, self.uncond_vector
return latent_states
class snake_case__ ( nn.Module ):
def __init__( self , lowerCamelCase ):
super().__init__()
__a = (config.num_hidden_layers + 1) // 5
__a = config.hidden_size
__a = 1
__a = nn.ModuleList(
[
BasicTransformerBlock(lowerCamelCase , lowerCamelCase , lowerCamelCase , activation_fn="gelu" , attention_bias=lowerCamelCase )
for _ in range(lowerCamelCase )
] )
def a__ ( self , lowerCamelCase ):
for block in self.blocks:
__a = block(lowerCamelCase )
return hidden_states
| 67 | """simple docstring"""
from urllib.parse import quote
import pytest
from datasets.utils.hub import hf_hub_url
@pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] )
@pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] )
@pytest.mark.parametrize("revision" , [None, "v2"] )
def _lowerCamelCase( a , a , a ):
__a = hf_hub_url(repo_id=a , path=a , revision=a )
assert url == F"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(a )}"
| 67 | 1 |
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from packaging import version
from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
add_code_sample_docstrings,
add_end_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
copy_func,
replace_return_docstrings,
)
from .generic import (
ContextManagers,
ExplicitEnum,
ModelOutput,
PaddingStrategy,
TensorType,
add_model_info_to_auto_map,
cached_property,
can_return_loss,
expand_dims,
find_labels,
flatten_dict,
infer_framework,
is_jax_tensor,
is_numpy_array,
is_tensor,
is_tf_symbolic_tensor,
is_tf_tensor,
is_torch_device,
is_torch_dtype,
is_torch_tensor,
reshape,
squeeze,
strtobool,
tensor_size,
to_numpy,
to_py_obj,
transpose,
working_or_temp_dir,
)
from .hub import (
CLOUDFRONT_DISTRIB_PREFIX,
DISABLE_TELEMETRY,
HF_MODULES_CACHE,
HUGGINGFACE_CO_PREFIX,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
PYTORCH_PRETRAINED_BERT_CACHE,
PYTORCH_TRANSFORMERS_CACHE,
S3_BUCKET_PREFIX,
TRANSFORMERS_CACHE,
TRANSFORMERS_DYNAMIC_MODULE_NAME,
EntryNotFoundError,
PushToHubMixin,
RepositoryNotFoundError,
RevisionNotFoundError,
cached_file,
default_cache_path,
define_sagemaker_information,
download_url,
extract_commit_hash,
get_cached_models,
get_file_from_repo,
get_full_repo_name,
has_file,
http_user_agent,
is_offline_mode,
is_remote_url,
move_cache,
send_example_telemetry,
try_to_load_from_cache,
)
from .import_utils import (
ENV_VARS_TRUE_AND_AUTO_VALUES,
ENV_VARS_TRUE_VALUES,
TORCH_FX_REQUIRED_VERSION,
USE_JAX,
USE_TF,
USE_TORCH,
DummyObject,
OptionalDependencyNotAvailable,
_LazyModule,
ccl_version,
direct_transformers_import,
get_torch_version,
is_accelerate_available,
is_apex_available,
is_bitsandbytes_available,
is_bsa_available,
is_coloredlogs_available,
is_cython_available,
is_datasets_available,
is_decord_available,
is_detectrona_available,
is_faiss_available,
is_flax_available,
is_ftfy_available,
is_in_notebook,
is_ipex_available,
is_jieba_available,
is_jumanpp_available,
is_kenlm_available,
is_keras_nlp_available,
is_librosa_available,
is_natten_available,
is_ninja_available,
is_onnx_available,
is_openai_available,
is_optimum_available,
is_pandas_available,
is_peft_available,
is_phonemizer_available,
is_protobuf_available,
is_psutil_available,
is_pyanvml_available,
is_pyctcdecode_available,
is_pytesseract_available,
is_pytest_available,
is_pytorch_quantization_available,
is_rjieba_available,
is_sacremoses_available,
is_safetensors_available,
is_sagemaker_dp_enabled,
is_sagemaker_mp_enabled,
is_scipy_available,
is_sentencepiece_available,
is_seqio_available,
is_sklearn_available,
is_soundfile_availble,
is_spacy_available,
is_speech_available,
is_sudachi_available,
is_tensorflow_probability_available,
is_tensorflow_text_available,
is_tfaonnx_available,
is_tf_available,
is_timm_available,
is_tokenizers_available,
is_torch_available,
is_torch_bfaa_available,
is_torch_bfaa_cpu_available,
is_torch_bfaa_gpu_available,
is_torch_compile_available,
is_torch_cuda_available,
is_torch_fx_available,
is_torch_fx_proxy,
is_torch_mps_available,
is_torch_neuroncore_available,
is_torch_tensorrt_fx_available,
is_torch_tfaa_available,
is_torch_tpu_available,
is_torchaudio_available,
is_torchdistx_available,
is_torchdynamo_available,
is_torchvision_available,
is_training_run_on_sagemaker,
is_vision_available,
requires_backends,
torch_only_method,
)
a_ :Any = "pytorch_model.bin"
a_ :List[str] = "pytorch_model.bin.index.json"
a_ :Optional[Any] = "adapter_config.json"
a_ :List[str] = "adapter_model.bin"
a_ :Union[str, Any] = "adapter_model.safetensors"
a_ :int = "tf_model.h5"
a_ :List[Any] = "tf_model.h5.index.json"
a_ :List[str] = "model.ckpt"
a_ :Optional[Any] = "flax_model.msgpack"
a_ :List[str] = "flax_model.msgpack.index.json"
a_ :str = "model.safetensors"
a_ :int = "model.safetensors.index.json"
a_ :List[str] = "config.json"
a_ :Any = "preprocessor_config.json"
a_ :Tuple = FEATURE_EXTRACTOR_NAME
a_ :List[str] = "generation_config.json"
a_ :List[Any] = "modelcard.json"
a_ :str = "▁"
a_ :Tuple = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility
a_ :Any = [
[[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too.
a_ :str = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
a_ :int = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]
def lowercase_ (A : str ):
if version.parse(lowerCAmelCase_ ) < version.parse(lowerCAmelCase_ ):
if "dev" in min_version:
snake_case__ : Dict = (
'This example requires a source install from HuggingFace Transformers (see '
'`https://huggingface.co/docs/transformers/installation#install-from-source`),'
)
else:
snake_case__ : Optional[Any] = F'''This example requires a minimum version of {min_version},'''
error_message += F''' but the version found is {__version__}.\n'''
raise ImportError(
error_message
+ 'Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other '
'versions of HuggingFace Transformers.' )
| 478 |
def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : int = 100_0000 ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple =set(range(3 ,lowerCAmelCase_ ,2 ) )
primes.add(2 )
for p in range(3 ,lowerCAmelCase_ ,2 ):
if p not in primes:
continue
primes.difference_update(set(range(p * p ,lowerCAmelCase_ ,lowerCAmelCase_ ) ) )
SCREAMING_SNAKE_CASE_ : List[str] =[float(lowerCAmelCase_ ) for n in range(limit + 1 )]
for p in primes:
for n in range(lowerCAmelCase_ ,limit + 1 ,lowerCAmelCase_ ):
phi[n] *= 1 - 1 / p
return int(sum(phi[2:] ) )
if __name__ == "__main__":
print(f"""{solution() = }""")
| 220 | 0 |
import re
from typing import Callable, List, Optional, Union
import tensorflow as tf
try:
from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
from tensorflow.keras.optimizers import Adam
class lowerCAmelCase_ ( tf.keras.optimizers.schedules.LearningRateSchedule ):
def __init__( self ,snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ = 1.0 ,snake_case__ = None ,):
super().__init__()
SCREAMING_SNAKE_CASE_ : str = initial_learning_rate
SCREAMING_SNAKE_CASE_ : int = warmup_steps
SCREAMING_SNAKE_CASE_ : int = power
SCREAMING_SNAKE_CASE_ : Optional[Any] = decay_schedule_fn
SCREAMING_SNAKE_CASE_ : Union[str, Any] = name
def __call__( self ,snake_case__ ):
with tf.name_scope(self.name or 'WarmUp' ) as name:
# Implements polynomial warmup. i.e., if global_step < warmup_steps, the
# learning rate will be `global_step/num_warmup_steps * init_lr`.
SCREAMING_SNAKE_CASE_ : Dict = tf.cast(snake_case__ ,tf.floataa )
SCREAMING_SNAKE_CASE_ : Dict = tf.cast(self.warmup_steps ,tf.floataa )
SCREAMING_SNAKE_CASE_ : Optional[int] = global_step_float / warmup_steps_float
SCREAMING_SNAKE_CASE_ : str = self.initial_learning_rate * tf.math.pow(snake_case__ ,self.power )
return tf.cond(
global_step_float < warmup_steps_float ,lambda: warmup_learning_rate ,lambda: self.decay_schedule_fn(step - self.warmup_steps ) ,name=snake_case__ ,)
def snake_case ( self ):
return {
"initial_learning_rate": self.initial_learning_rate,
"decay_schedule_fn": self.decay_schedule_fn,
"warmup_steps": self.warmup_steps,
"power": self.power,
"name": self.name,
}
def __UpperCAmelCase ( lowerCamelCase_ : float , lowerCamelCase_ : int , lowerCamelCase_ : int , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 0.9 , lowerCamelCase_ : float = 0.9_9_9 , lowerCamelCase_ : float = 1E-8 , lowerCamelCase_ : Optional[float] = None , lowerCamelCase_ : Optional[float] = None , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : float = 1.0 , lowerCamelCase_ : Optional[List[str]] = None , ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = tf.keras.optimizers.schedules.PolynomialDecay(
initial_learning_rate=lowerCamelCase_ , decay_steps=num_train_steps - num_warmup_steps , end_learning_rate=init_lr * min_lr_ratio , power=lowerCamelCase_ , )
if num_warmup_steps:
SCREAMING_SNAKE_CASE_ : Tuple = WarmUp(
initial_learning_rate=lowerCamelCase_ , decay_schedule_fn=lowerCamelCase_ , warmup_steps=lowerCamelCase_ , )
if weight_decay_rate > 0.0:
SCREAMING_SNAKE_CASE_ : Dict = AdamWeightDecay(
learning_rate=lowerCamelCase_ , weight_decay_rate=lowerCamelCase_ , beta_a=lowerCamelCase_ , beta_a=lowerCamelCase_ , epsilon=lowerCamelCase_ , clipnorm=lowerCamelCase_ , global_clipnorm=lowerCamelCase_ , exclude_from_weight_decay=['LayerNorm', 'layer_norm', 'bias'] , include_in_weight_decay=lowerCamelCase_ , )
else:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = tf.keras.optimizers.Adam(
learning_rate=lowerCamelCase_ , beta_a=lowerCamelCase_ , beta_a=lowerCamelCase_ , epsilon=lowerCamelCase_ , clipnorm=lowerCamelCase_ , global_clipnorm=lowerCamelCase_ , )
# We return the optimizer and the LR scheduler in order to better track the
# evolution of the LR independently of the optimizer.
return optimizer, lr_schedule
class lowerCAmelCase_ ( lowerCamelCase_ ):
def __init__( self ,snake_case__ = 0.001 ,snake_case__ = 0.9 ,snake_case__ = 0.999 ,snake_case__ = 1E-7 ,snake_case__ = False ,snake_case__ = 0.0 ,snake_case__ = None ,snake_case__ = None ,snake_case__ = "AdamWeightDecay" ,**snake_case__ ,):
super().__init__(snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ,**snake_case__ )
SCREAMING_SNAKE_CASE_ : int = weight_decay_rate
SCREAMING_SNAKE_CASE_ : Tuple = include_in_weight_decay
SCREAMING_SNAKE_CASE_ : Union[str, Any] = exclude_from_weight_decay
@classmethod
def snake_case ( cls ,snake_case__ ):
SCREAMING_SNAKE_CASE_ : str = {'WarmUp': WarmUp}
return super(snake_case__ ,cls ).from_config(snake_case__ ,custom_objects=snake_case__ )
def snake_case ( self ,snake_case__ ,snake_case__ ,snake_case__ ):
super(snake_case__ ,self )._prepare_local(snake_case__ ,snake_case__ ,snake_case__ )
SCREAMING_SNAKE_CASE_ : List[Any] = tf.constant(
self.weight_decay_rate ,name='adam_weight_decay_rate' )
def snake_case ( self ,snake_case__ ,snake_case__ ,snake_case__ ):
SCREAMING_SNAKE_CASE_ : Any = self._do_use_weight_decay(var.name )
if do_decay:
return var.assign_sub(
learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['weight_decay_rate'] ,use_locking=self._use_locking ,)
return tf.no_op()
def snake_case ( self ,snake_case__ ,snake_case__=None ,**snake_case__ ):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = list(zip(*snake_case__ ) )
return super(snake_case__ ,self ).apply_gradients(zip(snake_case__ ,snake_case__ ) ,name=snake_case__ ,**snake_case__ )
def snake_case ( self ,snake_case__ ,snake_case__ ,snake_case__ ):
if apply_state is None:
return self._decayed_lr_t[var_dtype], {}
SCREAMING_SNAKE_CASE_ : Union[str, Any] = apply_state or {}
SCREAMING_SNAKE_CASE_ : str = apply_state.get((var_device, var_dtype) )
if coefficients is None:
SCREAMING_SNAKE_CASE_ : str = self._fallback_apply_state(snake_case__ ,snake_case__ )
SCREAMING_SNAKE_CASE_ : Optional[Any] = coefficients
return coefficients["lr_t"], {"apply_state": apply_state}
def snake_case ( self ,snake_case__ ,snake_case__ ,snake_case__=None ):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self._get_lr(var.device ,var.dtype.base_dtype ,snake_case__ )
SCREAMING_SNAKE_CASE_ : int = self._decay_weights_op(snake_case__ ,snake_case__ ,snake_case__ )
with tf.control_dependencies([decay] ):
return super(snake_case__ ,self )._resource_apply_dense(snake_case__ ,snake_case__ ,**snake_case__ )
def snake_case ( self ,snake_case__ ,snake_case__ ,snake_case__ ,snake_case__=None ):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = self._get_lr(var.device ,var.dtype.base_dtype ,snake_case__ )
SCREAMING_SNAKE_CASE_ : str = self._decay_weights_op(snake_case__ ,snake_case__ ,snake_case__ )
with tf.control_dependencies([decay] ):
return super(snake_case__ ,self )._resource_apply_sparse(snake_case__ ,snake_case__ ,snake_case__ ,**snake_case__ )
def snake_case ( self ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = super().get_config()
config.update({'weight_decay_rate': self.weight_decay_rate} )
return config
def snake_case ( self ,snake_case__ ):
if self.weight_decay_rate == 0:
return False
if self._include_in_weight_decay:
for r in self._include_in_weight_decay:
if re.search(snake_case__ ,snake_case__ ) is not None:
return True
if self._exclude_from_weight_decay:
for r in self._exclude_from_weight_decay:
if re.search(snake_case__ ,snake_case__ ) is not None:
return False
return True
class lowerCAmelCase_ ( lowerCamelCase_ ):
def __init__( self ):
SCREAMING_SNAKE_CASE_ : Tuple = []
SCREAMING_SNAKE_CASE_ : List[Any] = None
@property
def snake_case ( self ):
if self._accum_steps is None:
SCREAMING_SNAKE_CASE_ : Tuple = tf.Variable(
tf.constant(0 ,dtype=tf.intaa ) ,trainable=snake_case__ ,synchronization=tf.VariableSynchronization.ON_READ ,aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA ,)
return self._accum_steps.value()
@property
def snake_case ( self ):
if not self._gradients:
raise ValueError('The accumulator should be called first to initialize the gradients' )
return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]
def __call__( self ,snake_case__ ):
if not self._gradients:
SCREAMING_SNAKE_CASE_ : Tuple = self.step # Create the step variable.
self._gradients.extend(
[
tf.Variable(
tf.zeros_like(snake_case__ ) ,trainable=snake_case__ ,synchronization=tf.VariableSynchronization.ON_READ ,aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA ,)
if gradient is not None
else gradient
for gradient in gradients
] )
if len(snake_case__ ) != len(self._gradients ):
raise ValueError(F'Expected {len(self._gradients )} gradients, but got {len(snake_case__ )}' )
for accum_gradient, gradient in zip(self._gradients ,snake_case__ ):
if accum_gradient is not None and gradient is not None:
accum_gradient.assign_add(snake_case__ )
self._accum_steps.assign_add(1 )
def snake_case ( self ):
if not self._gradients:
return
self._accum_steps.assign(0 )
for gradient in self._gradients:
if gradient is not None:
gradient.assign(tf.zeros_like(snake_case__ ) )
| 685 |
import json
import os
import unittest
from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class lowerCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ):
__a : Union[str, Any] = CLIPTokenizer
__a : List[str] = CLIPTokenizerFast
__a : List[str] = True
__a : Tuple = {}
__a : Tuple = False
def snake_case ( self ):
super().setUp()
# fmt: off
SCREAMING_SNAKE_CASE_ : List[Any] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
# fmt: on
SCREAMING_SNAKE_CASE_ : Union[str, Any] = dict(zip(snake_case__ ,range(len(snake_case__ ) ) ) )
SCREAMING_SNAKE_CASE_ : Any = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>']
SCREAMING_SNAKE_CASE_ : Any = {'unk_token': '<unk>'}
SCREAMING_SNAKE_CASE_ : Any = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] )
SCREAMING_SNAKE_CASE_ : Any = 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(snake_case__ ) + '\n' )
with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp:
fp.write('\n'.join(snake_case__ ) )
def snake_case ( self ,**snake_case__ ):
kwargs.update(self.special_tokens_map )
return CLIPTokenizer.from_pretrained(self.tmpdirname ,**snake_case__ )
def snake_case ( self ,**snake_case__ ):
kwargs.update(self.special_tokens_map )
return CLIPTokenizerFast.from_pretrained(self.tmpdirname ,**snake_case__ )
def snake_case ( self ,snake_case__ ):
SCREAMING_SNAKE_CASE_ : List[str] = 'lower newer'
SCREAMING_SNAKE_CASE_ : Tuple = 'lower newer'
return input_text, output_text
def snake_case ( self ):
SCREAMING_SNAKE_CASE_ : Tuple = CLIPTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map )
SCREAMING_SNAKE_CASE_ : List[Any] = 'lower newer'
SCREAMING_SNAKE_CASE_ : Optional[Any] = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>']
SCREAMING_SNAKE_CASE_ : Any = tokenizer.tokenize(snake_case__ )
self.assertListEqual(snake_case__ ,snake_case__ )
SCREAMING_SNAKE_CASE_ : Any = tokens + [tokenizer.unk_token]
SCREAMING_SNAKE_CASE_ : Optional[Any] = [10, 2, 16, 9, 3, 2, 16, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) ,snake_case__ )
@require_ftfy
def snake_case ( self ):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ):
SCREAMING_SNAKE_CASE_ : Any = self.tokenizer_class.from_pretrained(snake_case__ ,**snake_case__ )
SCREAMING_SNAKE_CASE_ : Any = self.rust_tokenizer_class.from_pretrained(snake_case__ ,**snake_case__ )
SCREAMING_SNAKE_CASE_ : Dict = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.'
SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer_s.tokenize(snake_case__ )
SCREAMING_SNAKE_CASE_ : str = tokenizer_r.tokenize(snake_case__ )
self.assertListEqual(snake_case__ ,snake_case__ )
# Test that the tokenization is identical on an example containing a character (Latin Small Letter A
# with Tilde) encoded in 2 different ways
SCREAMING_SNAKE_CASE_ : Dict = 'xa\u0303y' + ' ' + 'x\xe3y'
SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer_s.tokenize(snake_case__ )
SCREAMING_SNAKE_CASE_ : str = tokenizer_r.tokenize(snake_case__ )
self.assertListEqual(snake_case__ ,snake_case__ )
# Test that the tokenization is identical on unicode of space type
SCREAMING_SNAKE_CASE_ : Optional[Any] = [
'\u0009', # (horizontal tab, '\t')
'\u000B', # (vertical tab)
'\u000C', # (form feed)
'\u0020', # (space, ' ')
'\u200E', # (left-to-right mark):w
'\u200F', # (right-to-left mark)
]
for unicode_seq in spaces_unicodes:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = tokenizer_s.tokenize(snake_case__ )
SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer_r.tokenize(snake_case__ )
self.assertListEqual(snake_case__ ,snake_case__ )
# Test that the tokenization is identical on unicode of line break type
SCREAMING_SNAKE_CASE_ : Tuple = [
'\u000A', # (line feed, '\n')
'\r\n', # (carriage return and line feed, '\r\n')
'\u000D', # (carriage return, '\r')
'\r', # (carriage return, '\r')
'\u000D', # (carriage return, '\r')
'\u2028', # (line separator)
'\u2029', # (paragraph separator)
# "\u0085", # (next line)
]
# The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms
# it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a
# space (and thus into an empty list).
for unicode_seq in line_break_unicodes:
SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer_s.tokenize(snake_case__ )
SCREAMING_SNAKE_CASE_ : Tuple = tokenizer_r.tokenize(snake_case__ )
self.assertListEqual(snake_case__ ,snake_case__ )
def snake_case ( self ):
# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space`
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ):
SCREAMING_SNAKE_CASE_ : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name`
SCREAMING_SNAKE_CASE_ : Tuple = F'{text_of_1_token} {text_of_1_token}'
SCREAMING_SNAKE_CASE_ : Optional[int] = self.rust_tokenizer_class.from_pretrained(
snake_case__ ,use_fast=snake_case__ ,)
SCREAMING_SNAKE_CASE_ : str = tokenizer_r(snake_case__ ,return_offsets_mapping=snake_case__ ,add_special_tokens=snake_case__ )
self.assertEqual(encoding.offset_mapping[0] ,(0, len(snake_case__ )) )
self.assertEqual(
encoding.offset_mapping[1] ,(len(snake_case__ ) + 1, len(snake_case__ ) + 1 + len(snake_case__ )) ,)
SCREAMING_SNAKE_CASE_ : Union[str, Any] = F' {text}'
SCREAMING_SNAKE_CASE_ : Optional[int] = self.rust_tokenizer_class.from_pretrained(
snake_case__ ,use_fast=snake_case__ ,)
SCREAMING_SNAKE_CASE_ : int = tokenizer_r(snake_case__ ,return_offsets_mapping=snake_case__ ,add_special_tokens=snake_case__ )
self.assertEqual(encoding.offset_mapping[0] ,(1, 1 + len(snake_case__ )) )
self.assertEqual(
encoding.offset_mapping[1] ,(1 + len(snake_case__ ) + 1, 1 + len(snake_case__ ) + 1 + len(snake_case__ )) ,)
def snake_case ( self ):
# Test related to the breaking change introduced in transformers v4.17.0
# We need to check that an error in raised when the user try to load a previous version of the tokenizer.
with self.assertRaises(snake_case__ ) as context:
self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' )
self.assertTrue(
context.exception.args[0].startswith(
'The `backend_tokenizer` provided does not match the expected format.' ) )
@require_ftfy
def snake_case ( self ):
super().test_tokenization_python_rust_equals()
def snake_case ( self ):
# CLIP always lower cases letters
pass
| 685 | 1 |
'''simple docstring'''
from dataclasses import dataclass
from typing import Dict, Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder
@dataclass
class A_ (lowerCAmelCase_ ):
"""simple docstring"""
a__ = 42
class A_ (lowerCAmelCase_ , lowerCAmelCase_ ):
"""simple docstring"""
a__ = True
@register_to_config
def __init__( self :List[str] , lowerCAmelCase__ :int = 3 , lowerCAmelCase__ :int = 3 , lowerCAmelCase__ :Tuple[str] = ("DownEncoderBlock2D",) , lowerCAmelCase__ :Tuple[str] = ("UpDecoderBlock2D",) , lowerCAmelCase__ :Tuple[int] = (64,) , lowerCAmelCase__ :int = 1 , lowerCAmelCase__ :str = "silu" , lowerCAmelCase__ :int = 4 , lowerCAmelCase__ :int = 32 , lowerCAmelCase__ :int = 32 , lowerCAmelCase__ :float = 0.1_8_2_1_5 , ) -> List[Any]:
'''simple docstring'''
super().__init__()
# pass init params to Encoder
snake_case_ : Any = Encoder(
in_channels=lowercase__ , out_channels=lowercase__ , down_block_types=lowercase__ , block_out_channels=lowercase__ , layers_per_block=lowercase__ , act_fn=lowercase__ , norm_num_groups=lowercase__ , double_z=lowercase__ , )
# pass init params to Decoder
snake_case_ : Any = Decoder(
in_channels=lowercase__ , out_channels=lowercase__ , up_block_types=lowercase__ , block_out_channels=lowercase__ , layers_per_block=lowercase__ , norm_num_groups=lowercase__ , act_fn=lowercase__ , )
snake_case_ : int = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 )
snake_case_ : List[str] = nn.Convad(lowercase__ , lowercase__ , 1 )
snake_case_ : List[str] = False
snake_case_ : str = False
# only relevant if vae tiling is enabled
snake_case_ : List[Any] = self.config.sample_size
snake_case_ : Optional[Any] = (
self.config.sample_size[0]
if isinstance(self.config.sample_size , (list, tuple) )
else self.config.sample_size
)
snake_case_ : int = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) )
snake_case_ : Optional[int] = 0.2_5
def _A ( self :Tuple , lowerCAmelCase__ :Union[str, Any] , lowerCAmelCase__ :Tuple=False ) -> int:
'''simple docstring'''
if isinstance(lowercase__ , (Encoder, Decoder) ):
snake_case_ : Any = value
def _A ( self :Tuple , lowerCAmelCase__ :bool = True ) -> Dict:
'''simple docstring'''
snake_case_ : Union[str, Any] = use_tiling
def _A ( self :List[Any] ) -> List[Any]:
'''simple docstring'''
self.enable_tiling(lowercase__ )
def _A ( self :Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
snake_case_ : Optional[int] = True
def _A ( self :str ) -> Any:
'''simple docstring'''
snake_case_ : Union[str, Any] = False
@property
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
def _A ( self :List[str] ) -> List[str]:
'''simple docstring'''
snake_case_ : List[Any] = {}
def fn_recursive_add_processors(lowerCAmelCase__ :str , lowerCAmelCase__ :torch.nn.Module , lowerCAmelCase__ :Dict[str, AttentionProcessor] ):
if hasattr(lowercase__ , "set_processor" ):
snake_case_ : Tuple = module.processor
for sub_name, child in module.named_children():
fn_recursive_add_processors(F'''{name}.{sub_name}''' , lowercase__ , lowercase__ )
return processors
for name, module in self.named_children():
fn_recursive_add_processors(lowercase__ , lowercase__ , lowercase__ )
return processors
def _A ( self :int , lowerCAmelCase__ :Union[AttentionProcessor, Dict[str, AttentionProcessor]] ) -> Any:
'''simple docstring'''
snake_case_ : Optional[Any] = len(self.attn_processors.keys() )
if isinstance(lowercase__ , lowercase__ ) and len(lowercase__ ) != count:
raise ValueError(
F'''A dict of processors was passed, but the number of processors {len(lowercase__ )} does not match the'''
F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' )
def fn_recursive_attn_processor(lowerCAmelCase__ :str , lowerCAmelCase__ :torch.nn.Module , lowerCAmelCase__ :List[str] ):
if hasattr(lowercase__ , "set_processor" ):
if not isinstance(lowercase__ , lowercase__ ):
module.set_processor(lowercase__ )
else:
module.set_processor(processor.pop(F'''{name}.processor''' ) )
for sub_name, child in module.named_children():
fn_recursive_attn_processor(F'''{name}.{sub_name}''' , lowercase__ , lowercase__ )
for name, module in self.named_children():
fn_recursive_attn_processor(lowercase__ , lowercase__ , lowercase__ )
def _A ( self :Any ) -> Tuple:
'''simple docstring'''
self.set_attn_processor(AttnProcessor() )
@apply_forward_hook
def _A ( self :Optional[Any] , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :bool = True ) -> Tuple:
'''simple docstring'''
if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
return self.tiled_encode(lowercase__ , return_dict=lowercase__ )
if self.use_slicing and x.shape[0] > 1:
snake_case_ : Union[str, Any] = [self.encoder(lowercase__ ) for x_slice in x.split(1 )]
snake_case_ : Any = torch.cat(lowercase__ )
else:
snake_case_ : Tuple = self.encoder(lowercase__ )
snake_case_ : Optional[Any] = self.quant_conv(lowercase__ )
snake_case_ : Optional[Any] = DiagonalGaussianDistribution(lowercase__ )
if not return_dict:
return (posterior,)
return AutoencoderKLOutput(latent_dist=lowercase__ )
def _A ( self :Any , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :bool = True ) -> Tuple:
'''simple docstring'''
if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
return self.tiled_decode(lowercase__ , return_dict=lowercase__ )
snake_case_ : List[Any] = self.post_quant_conv(lowercase__ )
snake_case_ : Optional[Any] = self.decoder(lowercase__ )
if not return_dict:
return (dec,)
return DecoderOutput(sample=lowercase__ )
@apply_forward_hook
def _A ( self :Optional[int] , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :bool = True ) -> Any:
'''simple docstring'''
if self.use_slicing and z.shape[0] > 1:
snake_case_ : Optional[Any] = [self._decode(lowercase__ ).sample for z_slice in z.split(1 )]
snake_case_ : Union[str, Any] = torch.cat(lowercase__ )
else:
snake_case_ : Optional[Any] = self._decode(lowercase__ ).sample
if not return_dict:
return (decoded,)
return DecoderOutput(sample=lowercase__ )
def _A ( self :Optional[Any] , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :List[Any] ) -> str:
'''simple docstring'''
snake_case_ : Optional[int] = min(a.shape[2] , b.shape[2] , lowercase__ )
for y in range(lowercase__ ):
snake_case_ : str = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
return b
def _A ( self :Dict , lowerCAmelCase__ :Optional[int] , lowerCAmelCase__ :Optional[int] , lowerCAmelCase__ :List[str] ) -> Optional[int]:
'''simple docstring'''
snake_case_ : Any = min(a.shape[3] , b.shape[3] , lowercase__ )
for x in range(lowercase__ ):
snake_case_ : Any = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
return b
def _A ( self :Dict , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :bool = True ) -> Tuple:
'''simple docstring'''
snake_case_ : Tuple = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) )
snake_case_ : Optional[int] = int(self.tile_latent_min_size * self.tile_overlap_factor )
snake_case_ : Tuple = self.tile_latent_min_size - blend_extent
# Split the image into 512x512 tiles and encode them separately.
snake_case_ : int = []
for i in range(0 , x.shape[2] , lowercase__ ):
snake_case_ : List[Any] = []
for j in range(0 , x.shape[3] , lowercase__ ):
snake_case_ : int = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
snake_case_ : Union[str, Any] = self.encoder(lowercase__ )
snake_case_ : Dict = self.quant_conv(lowercase__ )
row.append(lowercase__ )
rows.append(lowercase__ )
snake_case_ : int = []
for i, row in enumerate(lowercase__ ):
snake_case_ : List[Any] = []
for j, tile in enumerate(lowercase__ ):
# blend the above tile and the left tile
# to the current tile and add the current tile to the result row
if i > 0:
snake_case_ : List[str] = self.blend_v(rows[i - 1][j] , lowercase__ , lowercase__ )
if j > 0:
snake_case_ : Any = self.blend_h(row[j - 1] , lowercase__ , lowercase__ )
result_row.append(tile[:, :, :row_limit, :row_limit] )
result_rows.append(torch.cat(lowercase__ , dim=3 ) )
snake_case_ : Optional[int] = torch.cat(lowercase__ , dim=2 )
snake_case_ : List[Any] = DiagonalGaussianDistribution(lowercase__ )
if not return_dict:
return (posterior,)
return AutoencoderKLOutput(latent_dist=lowercase__ )
def _A ( self :Dict , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :bool = True ) -> Any:
'''simple docstring'''
snake_case_ : Any = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) )
snake_case_ : Any = int(self.tile_sample_min_size * self.tile_overlap_factor )
snake_case_ : Any = self.tile_sample_min_size - blend_extent
# Split z into overlapping 64x64 tiles and decode them separately.
# The tiles have an overlap to avoid seams between tiles.
snake_case_ : Optional[int] = []
for i in range(0 , z.shape[2] , lowercase__ ):
snake_case_ : Union[str, Any] = []
for j in range(0 , z.shape[3] , lowercase__ ):
snake_case_ : int = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
snake_case_ : Optional[Any] = self.post_quant_conv(lowercase__ )
snake_case_ : Optional[int] = self.decoder(lowercase__ )
row.append(lowercase__ )
rows.append(lowercase__ )
snake_case_ : Tuple = []
for i, row in enumerate(lowercase__ ):
snake_case_ : Optional[int] = []
for j, tile in enumerate(lowercase__ ):
# blend the above tile and the left tile
# to the current tile and add the current tile to the result row
if i > 0:
snake_case_ : int = self.blend_v(rows[i - 1][j] , lowercase__ , lowercase__ )
if j > 0:
snake_case_ : Any = self.blend_h(row[j - 1] , lowercase__ , lowercase__ )
result_row.append(tile[:, :, :row_limit, :row_limit] )
result_rows.append(torch.cat(lowercase__ , dim=3 ) )
snake_case_ : Dict = torch.cat(lowercase__ , dim=2 )
if not return_dict:
return (dec,)
return DecoderOutput(sample=lowercase__ )
def _A ( self :str , lowerCAmelCase__ :torch.FloatTensor , lowerCAmelCase__ :bool = False , lowerCAmelCase__ :bool = True , lowerCAmelCase__ :Optional[torch.Generator] = None , ) -> Dict:
'''simple docstring'''
snake_case_ : Optional[Any] = sample
snake_case_ : Union[str, Any] = self.encode(lowercase__ ).latent_dist
if sample_posterior:
snake_case_ : List[str] = posterior.sample(generator=lowercase__ )
else:
snake_case_ : Dict = posterior.mode()
snake_case_ : Union[str, Any] = self.decode(lowercase__ ).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=lowercase__ )
| 653 |
"""simple docstring"""
import random
def snake_case__ ( _lowerCamelCase, _lowerCamelCase, _lowerCamelCase = False ) ->dict:
"""simple docstring"""
__lowercase : dict = {i: [] for i in range(_lowerCamelCase )}
# if probability is greater or equal than 1, then generate a complete graph
if probability >= 1:
return complete_graph(_lowerCamelCase )
# if probability is lower or equal than 0, then return a graph without edges
if probability <= 0:
return graph
# for each couple of nodes, add an edge from u to v
# if the number randomly generated is greater than probability probability
for i in range(_lowerCamelCase ):
for j in range(i + 1, _lowerCamelCase ):
if random.random() < probability:
graph[i].append(_lowerCamelCase )
if not directed:
# if the graph is undirected, add an edge in from j to i, either
graph[j].append(_lowerCamelCase )
return graph
def snake_case__ ( _lowerCamelCase ) ->dict:
"""simple docstring"""
return {
i: [j for j in range(_lowerCamelCase ) if i != j] for i in range(_lowerCamelCase )
}
if __name__ == "__main__":
import doctest
doctest.testmod()
| 575 | 0 |
'''simple docstring'''
def lowercase_ ( _lowercase = 10 ) -> str:
'''simple docstring'''
if not isinstance(_lowercase , _lowercase ) or n < 0:
raise ValueError('''Invalid input''' )
lowerCamelCase_ : Any = 10**n
lowerCamelCase_ : int = 28_433 * (pow(2 , 7_830_457 , _lowercase )) + 1
return str(number % modulus )
if __name__ == "__main__":
from doctest import testmod
testmod()
print(f'{solution(10) = }')
| 703 |
'''simple docstring'''
def lowercase_ ( _lowercase = 1_000 ) -> int:
'''simple docstring'''
lowerCamelCase_ : Dict = 2**power
lowerCamelCase_ : Union[str, Any] = str(_lowercase )
lowerCamelCase_ : Union[str, Any] = list(_lowercase )
lowerCamelCase_ : Dict = 0
for i in list_num:
sum_of_num += int(_lowercase )
return sum_of_num
if __name__ == "__main__":
__lowercase : Optional[Any] = int(input('''Enter the power of 2: ''').strip())
print('''2 ^ ''', power, ''' = ''', 2**power)
__lowercase : Tuple = solution(power)
print('''Sum of the digits is: ''', result)
| 357 | 0 |
"""simple docstring"""
import os
import pytest
from transformers.dynamic_module_utils import get_imports
_a = """
import os
"""
_a = """
def foo():
import os
return False
"""
_a = """
def foo():
def bar():
if True:
import os
return False
return bar()
"""
_a = """
import os
try:
import bar
except ImportError:
raise ValueError()
"""
_a = """
import os
def foo():
try:
import bar
except ImportError:
raise ValueError()
"""
_a = """
import os
try:
import bar
except (ImportError, AttributeError):
raise ValueError()
"""
_a = """
import os
try:
import bar
except ImportError as e:
raise ValueError()
"""
_a = """
import os
try:
import bar
except:
raise ValueError()
"""
_a = """
import os
try:
import bar
import baz
except ImportError:
raise ValueError()
"""
_a = """
import os
try:
import bar
import baz
except ImportError:
x = 1
raise ValueError()
"""
_a = [
TOP_LEVEL_IMPORT,
IMPORT_IN_FUNCTION,
DEEPLY_NESTED_IMPORT,
TOP_LEVEL_TRY_IMPORT,
GENERIC_EXCEPT_IMPORT,
MULTILINE_TRY_IMPORT,
MULTILINE_BOTH_IMPORT,
MULTIPLE_EXCEPTS_IMPORT,
EXCEPT_AS_IMPORT,
TRY_IMPORT_IN_FUNCTION,
]
@pytest.mark.parametrize('''case''', __snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = os.path.join(__snake_case, '''test_file.py''' )
with open(__snake_case, '''w''' ) as _tmp_file:
_tmp_file.write(__snake_case )
_UpperCamelCase = get_imports(__snake_case )
assert parsed_imports == ["os"]
| 19 |
from __future__ import annotations
from typing import Generic, TypeVar
__a : str = TypeVar("T")
class __lowercase ( Generic[T] ):
'''simple docstring'''
def __init__( self : Any , UpperCamelCase_ : T ):
"""simple docstring"""
__A = data
__A = self
__A = 0
class __lowercase ( Generic[T] ):
'''simple docstring'''
def __init__( self : Optional[Any] ):
"""simple docstring"""
__A = {}
def lowerCAmelCase_ ( self : Union[str, Any] , UpperCamelCase_ : T ):
"""simple docstring"""
__A = DisjointSetTreeNode(UpperCamelCase_ )
def lowerCAmelCase_ ( self : List[Any] , UpperCamelCase_ : T ):
"""simple docstring"""
__A = self.map[data]
if elem_ref != elem_ref.parent:
__A = self.find_set(elem_ref.parent.data )
return elem_ref.parent
def lowerCAmelCase_ ( self : int , UpperCamelCase_ : DisjointSetTreeNode[T] , UpperCamelCase_ : DisjointSetTreeNode[T] ):
"""simple docstring"""
if nodea.rank > nodea.rank:
__A = nodea
else:
__A = nodea
if nodea.rank == nodea.rank:
nodea.rank += 1
def lowerCAmelCase_ ( self : Tuple , UpperCamelCase_ : T , UpperCamelCase_ : T ):
"""simple docstring"""
self.link(self.find_set(UpperCamelCase_ ) , self.find_set(UpperCamelCase_ ) )
class __lowercase ( Generic[T] ):
'''simple docstring'''
def __init__( self : Optional[int] ):
"""simple docstring"""
__A = {}
def lowerCAmelCase_ ( self : int , UpperCamelCase_ : T ):
"""simple docstring"""
if node not in self.connections:
__A = {}
def lowerCAmelCase_ ( self : Dict , UpperCamelCase_ : T , UpperCamelCase_ : T , UpperCamelCase_ : int ):
"""simple docstring"""
self.add_node(UpperCamelCase_ )
self.add_node(UpperCamelCase_ )
__A = weight
__A = weight
def lowerCAmelCase_ ( self : Dict ):
"""simple docstring"""
__A = []
__A = set()
for start in self.connections:
for end in self.connections[start]:
if (start, end) not in seen:
seen.add((end, start) )
edges.append((start, end, self.connections[start][end]) )
edges.sort(key=lambda UpperCamelCase_ : x[2] )
# creating the disjoint set
__A = DisjointSetTree[T]()
for node in self.connections:
disjoint_set.make_set(UpperCamelCase_ )
# MST generation
__A = 0
__A = 0
__A = GraphUndirectedWeighted[T]()
while num_edges < len(self.connections ) - 1:
__A , __A , __A = edges[index]
index += 1
__A = disjoint_set.find_set(UpperCamelCase_ )
__A = disjoint_set.find_set(UpperCamelCase_ )
if parent_u != parent_v:
num_edges += 1
graph.add_edge(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
disjoint_set.union(UpperCamelCase_ , UpperCamelCase_ )
return graph
| 637 | 0 |
'''simple docstring'''
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
__A : Optional[Any] = trt.Logger(trt.Logger.WARNING)
__A : Optional[int] = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
__A : List[str] = logging.getLogger(__name__)
__A : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--onnx_model_path',
default=None,
type=str,
required=True,
help='Path to ONNX model: ',
)
parser.add_argument(
'--output_dir',
default=None,
type=str,
required=True,
help='The output directory where the model checkpoints and predictions will be written.',
)
# Other parameters
parser.add_argument(
'--tokenizer_name',
default='',
type=str,
required=True,
help='Pretrained tokenizer name or path if not the same as model_name',
)
parser.add_argument(
'--version_2_with_negative',
action='store_true',
help='If true, the SQuAD examples contain some that do not have an answer.',
)
parser.add_argument(
'--null_score_diff_threshold',
type=float,
default=0.0,
help='If null_score - best_non_null is greater than the threshold predict null.',
)
parser.add_argument(
'--max_seq_length',
default=3_84,
type=int,
help=(
'The maximum total input sequence length after WordPiece tokenization. Sequences '
'longer than this will be truncated, and sequences shorter than this will be padded.'
),
)
parser.add_argument(
'--doc_stride',
default=1_28,
type=int,
help='When splitting up a long document into chunks, how much stride to take between chunks.',
)
parser.add_argument('--per_device_eval_batch_size', default=8, type=int, help='Batch size per GPU/CPU for evaluation.')
parser.add_argument(
'--n_best_size',
default=20,
type=int,
help='The total number of n-best predictions to generate in the nbest_predictions.json output file.',
)
parser.add_argument(
'--max_answer_length',
default=30,
type=int,
help=(
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
),
)
parser.add_argument('--seed', type=int, default=42, help='random seed for initialization')
parser.add_argument(
'--dataset_name',
type=str,
default=None,
required=True,
help='The name of the dataset to use (via the datasets library).',
)
parser.add_argument(
'--dataset_config_name',
type=str,
default=None,
help='The configuration name of the dataset to use (via the datasets library).',
)
parser.add_argument(
'--preprocessing_num_workers', type=int, default=4, help='A csv or a json file containing the training data.'
)
parser.add_argument('--overwrite_cache', action='store_true', help='Overwrite the cached training and evaluation sets')
parser.add_argument(
'--fp16',
action='store_true',
help='Whether to use 16-bit (mixed) precision instead of 32-bit',
)
parser.add_argument(
'--int8',
action='store_true',
help='Whether to use INT8',
)
__A : Union[str, Any] = parser.parse_args()
if args.tokenizer_name:
__A : Tuple = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
'You are instantiating a new tokenizer from scratch. This is not supported by this script.'
'You can do it from another script, save it, and load it from here, using --tokenizer_name.'
)
logger.info('Training/evaluation parameters %s', args)
__A : Tuple = args.per_device_eval_batch_size
__A : Optional[int] = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
__A : Optional[int] = True
__A : Optional[Any] = 'temp_engine/bert-fp32.engine'
if args.fpaa:
__A : Optional[int] = 'temp_engine/bert-fp16.engine'
if args.inta:
__A : str = 'temp_engine/bert-int8.engine'
# import ONNX file
if not os.path.exists('temp_engine'):
os.makedirs('temp_engine')
__A : str = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, 'rb') as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
__A : Any = [network.get_input(i) for i in range(network.num_inputs)]
__A : Optional[int] = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
__A : Tuple = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
__A : Optional[int] = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
__A : int = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, 'wb') as f:
f.write(engine.serialize())
def lowerCAmelCase_ ( a : str , a : str , a : Any , a : Optional[Any] , a : List[Any] , a : Union[str, Any] , a : Dict , a : Tuple ):
a__ = np.asarray(inputs['input_ids'] , dtype=np.intaa )
a__ = np.asarray(inputs['attention_mask'] , dtype=np.intaa )
a__ = np.asarray(inputs['token_type_ids'] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , __SCREAMING_SNAKE_CASE )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , __SCREAMING_SNAKE_CASE )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , __SCREAMING_SNAKE_CASE )
# start time
a__ = time.time()
# Run inference
context.execute_async(
bindings=[int(__SCREAMING_SNAKE_CASE ) for d_inp in d_inputs] + [int(__SCREAMING_SNAKE_CASE ), int(__SCREAMING_SNAKE_CASE )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
cuda.memcpy_dtoh_async(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
# Synchronize the stream and take time
stream.synchronize()
# end time
a__ = time.time()
a__ = end_time - start_time
a__ = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
__A : Tuple = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
__A : str = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError('Evaluation requires a dataset name')
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
__A : str = raw_datasets['validation'].column_names
__A : List[Any] = 'question' if 'question' in column_names else column_names[0]
__A : Any = 'context' if 'context' in column_names else column_names[1]
__A : Optional[int] = 'answers' if 'answers' in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
__A : str = tokenizer.padding_side == 'right'
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
F"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the"""
F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""
)
__A : Optional[Any] = min(args.max_seq_length, tokenizer.model_max_length)
def lowerCAmelCase_ ( a : List[Any] ):
a__ = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
a__ = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='only_second' if pad_on_right else 'only_first' , max_length=__SCREAMING_SNAKE_CASE , stride=args.doc_stride , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , padding='max_length' , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
a__ = tokenized_examples.pop('overflow_to_sample_mapping' )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
a__ = []
for i in range(len(tokenized_examples['input_ids'] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
a__ = tokenized_examples.sequence_ids(__SCREAMING_SNAKE_CASE )
a__ = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
a__ = sample_mapping[i]
tokenized_examples["example_id"].append(examples['id'][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
a__ = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples['offset_mapping'][i] )
]
return tokenized_examples
__A : str = raw_datasets['validation']
# Validation Feature Creation
__A : Tuple = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc='Running tokenizer on validation dataset',
)
__A : Optional[Any] = default_data_collator
__A : List[Any] = eval_dataset.remove_columns(['example_id', 'offset_mapping'])
__A : Tuple = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def lowerCAmelCase_ ( a : Union[str, Any] , a : Union[str, Any] , a : Dict , a : Union[str, Any]="eval" ):
a__ = postprocess_qa_predictions(
examples=__SCREAMING_SNAKE_CASE , features=__SCREAMING_SNAKE_CASE , predictions=__SCREAMING_SNAKE_CASE , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=__SCREAMING_SNAKE_CASE , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
a__ = [
{"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items()
]
else:
a__ = [{"id": k, "prediction_text": v} for k, v in predictions.items()]
a__ = [{"id": ex["id"], "answers": ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=__SCREAMING_SNAKE_CASE , label_ids=__SCREAMING_SNAKE_CASE )
__A : Optional[Any] = load_metric('squad_v2' if args.version_2_with_negative else 'squad')
# Evaluation!
logger.info('Loading ONNX model %s for evaluation', args.onnx_model_path)
with open(engine_name, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def lowerCAmelCase_ ( a : Tuple ):
return trt.volume(engine.get_binding_shape(__SCREAMING_SNAKE_CASE ) ) * engine.get_binding_dtype(__SCREAMING_SNAKE_CASE ).itemsize
# Allocate device memory for inputs and outputs.
__A : Optional[int] = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
__A : List[Any] = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
__A : str = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
__A : Dict = cuda.mem_alloc(h_outputa.nbytes)
__A : int = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
__A : Optional[int] = cuda.Stream()
# Evaluation
logger.info('***** Running Evaluation *****')
logger.info(F""" Num examples = {len(eval_dataset)}""")
logger.info(F""" Batch size = {args.per_device_eval_batch_size}""")
__A : Dict = 0.0
__A : List[Any] = 0
__A : List[Any] = timeit.default_timer()
__A : Optional[int] = None
for step, batch in enumerate(eval_dataloader):
__A , __A : Optional[Any] = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
__A , __A : List[str] = outputs
__A : int = torch.tensor(start_logits)
__A : str = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
__A : Optional[int] = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00)
__A : Tuple = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00)
__A : List[Any] = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
__A : Dict = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00)
if all_preds is not None:
__A : Any = nested_truncate(all_preds, len(eval_dataset))
__A : Optional[Any] = timeit.default_timer() - start_time
logger.info(' Evaluation done in total %f secs (%f sec per example)', evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info('Average Inference Time = {:.3f} ms'.format(total_time * 10_00 / niter))
logger.info('Total Inference Time = {:.3f} ms'.format(total_time * 10_00))
logger.info('Total Number of Inference = %d', niter)
__A : int = post_processing_function(eval_examples, eval_dataset, all_preds)
__A : Any = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(F"""Evaluation metrics: {eval_metric}""")
| 704 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
is_valid_image,
to_numpy_array,
valid_images,
)
from ...utils import logging
if is_vision_available():
import PIL
__A : Optional[int] = logging.get_logger(__name__)
def lowerCAmelCase_ ( a : List[Any] ):
if isinstance(a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ):
return videos
elif isinstance(a , (list, tuple) ) and is_valid_image(videos[0] ):
return [videos]
elif is_valid_image(a ):
return [[videos]]
raise ValueError(f'''Could not make batched video from {videos}''' )
class _UpperCamelCase ( _A ):
'''simple docstring'''
SCREAMING_SNAKE_CASE:List[str] = ['pixel_values']
def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = None , _a = True , _a = 1 / 255 , _a = True , _a = True , _a = None , _a = None , **_a , ):
"""simple docstring"""
super().__init__(**_a )
a__ = size if size is not None else {'shortest_edge': 256}
a__ = get_size_dict(_a , default_to_square=_a )
a__ = crop_size if crop_size is not None else {'height': 224, 'width': 224}
a__ = get_size_dict(_a , param_name='crop_size' )
a__ = do_resize
a__ = size
a__ = do_center_crop
a__ = crop_size
a__ = resample
a__ = do_rescale
a__ = rescale_factor
a__ = offset
a__ = do_normalize
a__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
a__ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def lowercase__ ( self , _a , _a , _a = PILImageResampling.BILINEAR , _a = None , **_a , ):
"""simple docstring"""
a__ = get_size_dict(_a , default_to_square=_a )
if "shortest_edge" in size:
a__ = get_resize_output_image_size(_a , size['shortest_edge'] , default_to_square=_a )
elif "height" in size and "width" in size:
a__ = (size['height'], size['width'])
else:
raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' )
return resize(_a , size=_a , resample=_a , data_format=_a , **_a )
def lowercase__ ( self , _a , _a , _a = None , **_a , ):
"""simple docstring"""
a__ = get_size_dict(_a )
if "height" not in size or "width" not in size:
raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' )
return center_crop(_a , size=(size['height'], size['width']) , data_format=_a , **_a )
def lowercase__ ( self , _a , _a , _a = True , _a = None , **_a , ):
"""simple docstring"""
a__ = image.astype(np.floataa )
if offset:
a__ = image - (scale / 2)
return rescale(_a , scale=_a , data_format=_a , **_a )
def lowercase__ ( self , _a , _a , _a , _a = None , **_a , ):
"""simple docstring"""
return normalize(_a , mean=_a , std=_a , data_format=_a , **_a )
def lowercase__ ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , ):
"""simple docstring"""
if do_resize and size is None or resample is None:
raise ValueError('Size and resample must be specified if do_resize is True.' )
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.' )
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.' )
if offset and not do_rescale:
raise ValueError('For offset, do_rescale must also be set to True.' )
# All transformations expect numpy arrays.
a__ = to_numpy_array(_a )
if do_resize:
a__ = self.resize(image=_a , size=_a , resample=_a )
if do_center_crop:
a__ = self.center_crop(_a , size=_a )
if do_rescale:
a__ = self.rescale(image=_a , scale=_a , offset=_a )
if do_normalize:
a__ = self.normalize(image=_a , mean=_a , std=_a )
a__ = to_channel_dimension_format(_a , _a )
return image
def lowercase__ ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ):
"""simple docstring"""
a__ = do_resize if do_resize is not None else self.do_resize
a__ = resample if resample is not None else self.resample
a__ = do_center_crop if do_center_crop is not None else self.do_center_crop
a__ = do_rescale if do_rescale is not None else self.do_rescale
a__ = rescale_factor if rescale_factor is not None else self.rescale_factor
a__ = offset if offset is not None else self.offset
a__ = do_normalize if do_normalize is not None else self.do_normalize
a__ = image_mean if image_mean is not None else self.image_mean
a__ = image_std if image_std is not None else self.image_std
a__ = size if size is not None else self.size
a__ = get_size_dict(_a , default_to_square=_a )
a__ = crop_size if crop_size is not None else self.crop_size
a__ = get_size_dict(_a , param_name='crop_size' )
if not valid_images(_a ):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.' )
a__ = make_batched(_a )
a__ = [
[
self._preprocess_image(
image=_a , do_resize=_a , size=_a , resample=_a , do_center_crop=_a , crop_size=_a , do_rescale=_a , rescale_factor=_a , offset=_a , do_normalize=_a , image_mean=_a , image_std=_a , data_format=_a , )
for img in video
]
for video in videos
]
a__ = {'pixel_values': videos}
return BatchFeature(data=_a , tensor_type=_a )
| 126 | 0 |
import subprocess
import sys
from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch
class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ):
'''simple docstring'''
@require_torch
def lowerCAmelCase_ ( self : int ):
# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
# while running an external program
# python one-liner segments
# this must be loaded before socket.socket is monkey-patched
SCREAMING_SNAKE_CASE_ = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n '
SCREAMING_SNAKE_CASE_ = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n '
SCREAMING_SNAKE_CASE_ = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n '
# Force fetching the files so that we can use the cache
SCREAMING_SNAKE_CASE_ = 'hf-internal-testing/tiny-random-bert'
BertConfig.from_pretrained(_lowerCAmelCase )
BertModel.from_pretrained(_lowerCAmelCase )
BertTokenizer.from_pretrained(_lowerCAmelCase )
pipeline(task='fill-mask' , model=_lowerCAmelCase )
# baseline - just load from_pretrained with normal network
SCREAMING_SNAKE_CASE_ = [sys.executable, '-c', '\n'.join([load, run, mock] )]
# should succeed
SCREAMING_SNAKE_CASE_ = self.get_env()
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
SCREAMING_SNAKE_CASE_ = '1'
SCREAMING_SNAKE_CASE_ = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('success' , result.stdout.decode() )
@require_torch
def lowerCAmelCase_ ( self : Tuple ):
# python one-liner segments
# this must be loaded before socket.socket is monkey-patched
SCREAMING_SNAKE_CASE_ = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n '
SCREAMING_SNAKE_CASE_ = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n '
SCREAMING_SNAKE_CASE_ = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n '
# Force fetching the files so that we can use the cache
SCREAMING_SNAKE_CASE_ = 'hf-internal-testing/tiny-random-bert'
BertConfig.from_pretrained(_lowerCAmelCase )
BertModel.from_pretrained(_lowerCAmelCase )
BertTokenizer.from_pretrained(_lowerCAmelCase )
pipeline(task='fill-mask' , model=_lowerCAmelCase )
# baseline - just load from_pretrained with normal network
SCREAMING_SNAKE_CASE_ = [sys.executable, '-c', '\n'.join([load, run, mock] )]
# should succeed
SCREAMING_SNAKE_CASE_ = self.get_env()
SCREAMING_SNAKE_CASE_ = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('success' , result.stdout.decode() )
@require_torch
def lowerCAmelCase_ ( self : List[str] ):
# this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
# `transformers` is loaded, and it's too late for inside pytest - so we are changing it
# while running an external program
# python one-liner segments
# this must be loaded before socket.socket is monkey-patched
SCREAMING_SNAKE_CASE_ = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n '
SCREAMING_SNAKE_CASE_ = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n '
SCREAMING_SNAKE_CASE_ = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n '
# baseline - just load from_pretrained with normal network
SCREAMING_SNAKE_CASE_ = [sys.executable, '-c', '\n'.join([load, run] )]
# should succeed
SCREAMING_SNAKE_CASE_ = self.get_env()
SCREAMING_SNAKE_CASE_ = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('success' , result.stdout.decode() )
# next emulate no network
SCREAMING_SNAKE_CASE_ = [sys.executable, '-c', '\n'.join([load, mock, run] )]
# Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
# env["TRANSFORMERS_OFFLINE"] = "0"
# result = subprocess.run(cmd, env=env, check=False, capture_output=True)
# self.assertEqual(result.returncode, 1, result.stderr)
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
SCREAMING_SNAKE_CASE_ = '1'
SCREAMING_SNAKE_CASE_ = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('success' , result.stdout.decode() )
@require_torch
def lowerCAmelCase_ ( self : Any ):
SCREAMING_SNAKE_CASE_ = '\nfrom transformers import pipeline\n '
SCREAMING_SNAKE_CASE_ = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n '
SCREAMING_SNAKE_CASE_ = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n '
SCREAMING_SNAKE_CASE_ = self.get_env()
SCREAMING_SNAKE_CASE_ = '1'
SCREAMING_SNAKE_CASE_ = [sys.executable, '-c', '\n'.join([load, mock, run] )]
SCREAMING_SNAKE_CASE_ = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 1 , result.stderr )
self.assertIn(
'You cannot infer task automatically within `pipeline` when using offline mode' , result.stderr.decode().replace('\n' , '' ) , )
@require_torch
def lowerCAmelCase_ ( self : Optional[int] ):
SCREAMING_SNAKE_CASE_ = '\nfrom transformers import AutoModel\n '
SCREAMING_SNAKE_CASE_ = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n '
# baseline - just load from_pretrained with normal network
SCREAMING_SNAKE_CASE_ = [sys.executable, '-c', '\n'.join([load, run] )]
# should succeed
SCREAMING_SNAKE_CASE_ = self.get_env()
SCREAMING_SNAKE_CASE_ = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('success' , result.stdout.decode() )
# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
SCREAMING_SNAKE_CASE_ = '1'
SCREAMING_SNAKE_CASE_ = subprocess.run(_lowerCAmelCase , env=_lowerCAmelCase , check=_lowerCAmelCase , capture_output=_lowerCAmelCase )
self.assertEqual(result.returncode , 0 , result.stderr )
self.assertIn('success' , result.stdout.decode() ) | 31 |
'''simple docstring'''
def a__ ( _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : list[int] ) -> tuple[float, float]:
"""simple docstring"""
if not len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) == 3:
raise ValueError("Please enter a valid equation." )
if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0:
raise ValueError("Both a & b of two equations can't be zero." )
# Extract the coefficients
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = equationa
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = equationa
# Calculate the determinants of the matrices
UpperCAmelCase_ : Optional[int] = aa * ba - aa * ba
UpperCAmelCase_ : Optional[int] = ca * ba - ca * ba
UpperCAmelCase_ : Any = aa * ca - aa * ca
# Check if the system of linear equations has a solution (using Cramer's rule)
if determinant == 0:
if determinant_x == determinant_y == 0:
raise ValueError("Infinite solutions. (Consistent system)" )
else:
raise ValueError("No solution. (Inconsistent system)" )
else:
if determinant_x == determinant_y == 0:
# Trivial solution (Inconsistent system)
return (0.0, 0.0)
else:
UpperCAmelCase_ : Optional[int] = determinant_x / determinant
UpperCAmelCase_ : List[Any] = determinant_y / determinant
# Non-Trivial Solution (Consistent system)
return (x, y)
| 71 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A_ : Union[str, Any] = logging.get_logger(__name__)
A_ : Union[str, Any] = {
"transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json",
}
class a_ ( snake_case_ ):
'''simple docstring'''
lowerCamelCase__ : Any = 'transfo-xl'
lowerCamelCase__ : str = ['mems']
lowerCamelCase__ : int = {
'n_token': 'vocab_size',
'hidden_size': 'd_model',
'num_attention_heads': 'n_head',
'num_hidden_layers': 'n_layer',
}
def __init__(self, lowerCamelCase_=2_6_7_7_3_5, lowerCamelCase_=[2_0_0_0_0, 4_0_0_0_0, 2_0_0_0_0_0], lowerCamelCase_=1_0_2_4, lowerCamelCase_=1_0_2_4, lowerCamelCase_=1_6, lowerCamelCase_=6_4, lowerCamelCase_=4_0_9_6, lowerCamelCase_=4, lowerCamelCase_=False, lowerCamelCase_=1_8, lowerCamelCase_=1_6_0_0, lowerCamelCase_=1_0_0_0, lowerCamelCase_=True, lowerCamelCase_=True, lowerCamelCase_=0, lowerCamelCase_=-1, lowerCamelCase_=True, lowerCamelCase_=0.1, lowerCamelCase_=0.0, lowerCamelCase_=True, lowerCamelCase_="normal", lowerCamelCase_=0.01, lowerCamelCase_=0.01, lowerCamelCase_=0.02, lowerCamelCase_=1e-5, lowerCamelCase_=0, **lowerCamelCase_, ):
'''simple docstring'''
lowerCamelCase__ : Dict = vocab_size
lowerCamelCase__ : Dict = []
self.cutoffs.extend(lowerCamelCase_ )
if proj_share_all_but_first:
lowerCamelCase__ : Dict = [False] + [True] * len(self.cutoffs )
else:
lowerCamelCase__ : Tuple = [False] + [False] * len(self.cutoffs )
lowerCamelCase__ : Union[str, Any] = d_model
lowerCamelCase__ : Optional[Any] = d_embed
lowerCamelCase__ : Optional[Any] = d_head
lowerCamelCase__ : Optional[int] = d_inner
lowerCamelCase__ : Optional[Any] = div_val
lowerCamelCase__ : List[str] = pre_lnorm
lowerCamelCase__ : List[Any] = n_layer
lowerCamelCase__ : Tuple = n_head
lowerCamelCase__ : Union[str, Any] = mem_len
lowerCamelCase__ : str = same_length
lowerCamelCase__ : Tuple = attn_type
lowerCamelCase__ : Union[str, Any] = clamp_len
lowerCamelCase__ : List[Any] = sample_softmax
lowerCamelCase__ : List[Any] = adaptive
lowerCamelCase__ : List[Any] = dropout
lowerCamelCase__ : int = dropatt
lowerCamelCase__ : Dict = untie_r
lowerCamelCase__ : Tuple = init
lowerCamelCase__ : Union[str, Any] = init_range
lowerCamelCase__ : Union[str, Any] = proj_init_std
lowerCamelCase__ : Union[str, Any] = init_std
lowerCamelCase__ : str = layer_norm_epsilon
super().__init__(eos_token_id=lowerCamelCase_, **lowerCamelCase_ )
@property
def a__ (self ):
'''simple docstring'''
logger.info(f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
return -1
@max_position_embeddings.setter
def a__ (self, lowerCamelCase_ ):
'''simple docstring'''
raise NotImplementedError(
f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
| 696 |
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class a_ ( metaclass=snake_case_ ):
'''simple docstring'''
lowerCamelCase__ : str = ['speech']
def __init__(self, *lowerCamelCase_, **lowerCamelCase_ ):
'''simple docstring'''
requires_backends(self, ['speech'] )
class a_ ( metaclass=snake_case_ ):
'''simple docstring'''
lowerCamelCase__ : Optional[Any] = ['speech']
def __init__(self, *lowerCamelCase_, **lowerCamelCase_ ):
'''simple docstring'''
requires_backends(self, ['speech'] )
| 696 | 1 |
'''simple docstring'''
import json
import logging
import os
import sys
from time import time
from unittest.mock import patch
from transformers.testing_utils import TestCasePlus, require_torch_tpu
logging.basicConfig(level=logging.DEBUG)
lowerCAmelCase : Optional[Any] = logging.getLogger()
def A_( A : Dict):
UpperCamelCase = {}
UpperCamelCase = os.path.join(A , 'all_results.json')
if os.path.exists(A):
with open(A , 'r') as f:
UpperCamelCase = json.load(A)
else:
raise ValueError(f'''can\'t find {path}''')
return results
lowerCAmelCase : Optional[Any] = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
@require_torch_tpu
class SCREAMING_SNAKE_CASE__ ( snake_case_):
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
import xla_spawn
UpperCamelCase = self.get_auto_remove_tmp_dir()
UpperCamelCase = F'''
./examples/pytorch/text-classification/run_glue.py
--num_cores=8
./examples/pytorch/text-classification/run_glue.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--overwrite_output_dir
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--do_train
--do_eval
--debug tpu_metrics_debug
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--max_steps=10
--warmup_steps=2
--seed=42
--max_seq_length=128
'''.split()
with patch.object(A_ , 'argv' , A_ ):
UpperCamelCase = time()
xla_spawn.main()
UpperCamelCase = time()
UpperCamelCase = get_results(A_ )
self.assertGreaterEqual(result['eval_accuracy'] , 0.75 )
# Assert that the script takes less than 500 seconds to make sure it doesn't hang.
self.assertLess(end - start , 500 )
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
import xla_spawn
UpperCamelCase = '\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n '.split()
with patch.object(A_ , 'argv' , A_ ):
xla_spawn.main()
| 3 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowercase_ : str = {'''configuration_sew''': ['''SEW_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SEWConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ : Optional[int] = [
'''SEW_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''SEWForCTC''',
'''SEWForSequenceClassification''',
'''SEWModel''',
'''SEWPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_sew import (
SEW_PRETRAINED_MODEL_ARCHIVE_LIST,
SEWForCTC,
SEWForSequenceClassification,
SEWModel,
SEWPreTrainedModel,
)
else:
import sys
lowercase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 588 | 0 |
"""simple docstring"""
def __UpperCAmelCase ( _snake_case : list[list[float]] ):
_lowercase = []
for data in source_data:
for i, el in enumerate(_snake_case ):
if len(_snake_case ) < i + 1:
data_lists.append([] )
data_lists[i].append(float(_snake_case ) )
return data_lists
def __UpperCAmelCase ( _snake_case : list[list[float]], _snake_case : list[int] ):
_lowercase = []
for dlist, weight in zip(_snake_case, _snake_case ):
_lowercase = min(_snake_case )
_lowercase = max(_snake_case )
_lowercase = []
# for weight 0 score is 1 - actual score
if weight == 0:
for item in dlist:
try:
score.append(1 - ((item - mind) / (maxd - mind)) )
except ZeroDivisionError:
score.append(1 )
elif weight == 1:
for item in dlist:
try:
score.append((item - mind) / (maxd - mind) )
except ZeroDivisionError:
score.append(0 )
# weight not 0 or 1
else:
_lowercase = f"""Invalid weight of {weight:f} provided"""
raise ValueError(_snake_case )
score_lists.append(_snake_case )
return score_lists
def __UpperCAmelCase ( _snake_case : list[list[float]] ):
_lowercase = [0 for i in range(len(score_lists[0] ) )]
for slist in score_lists:
for j, ele in enumerate(_snake_case ):
_lowercase = final_scores[j] + ele
return final_scores
def __UpperCAmelCase ( _snake_case : list[list[float]], _snake_case : list[int] ):
_lowercase = get_data(_snake_case )
_lowercase = calculate_each_score(_snake_case, _snake_case )
_lowercase = generate_final_scores(_snake_case )
# append scores to source data
for i, ele in enumerate(_snake_case ):
source_data[i].append(_snake_case )
return source_data | 227 | """simple docstring"""
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__UpperCamelCase : List[str] = logging.getLogger(__name__)
__UpperCamelCase : List[Any] = "Hello world! cécé herlolip"
__UpperCamelCase : Any = namedtuple(
"BertAbsConfig",
[
"temp_dir",
"large",
"use_bert_emb",
"finetune_bert",
"encoder",
"share_emb",
"max_pos",
"enc_layers",
"enc_hidden_size",
"enc_heads",
"enc_ff_size",
"enc_dropout",
"dec_layers",
"dec_hidden_size",
"dec_heads",
"dec_ff_size",
"dec_dropout",
],
)
def __UpperCAmelCase ( _snake_case : Union[str, Any], _snake_case : str ):
_lowercase = BertAbsConfig(
temp_dir=".", finetune_bert=_snake_case, large=_snake_case, share_emb=_snake_case, use_bert_emb=_snake_case, encoder="bert", max_pos=5_1_2, enc_layers=6, enc_hidden_size=5_1_2, enc_heads=8, enc_ff_size=5_1_2, enc_dropout=0.2, dec_layers=6, dec_hidden_size=7_6_8, dec_heads=8, dec_ff_size=2_0_4_8, dec_dropout=0.2, )
_lowercase = torch.load(_snake_case, lambda _snake_case, _snake_case : storage )
_lowercase = AbsSummarizer(_snake_case, torch.device("cpu" ), _snake_case )
original.eval()
_lowercase = BertAbsSummarizer(_snake_case, torch.device("cpu" ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info("convert the model" )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info("Make sure that the models' outputs are identical" )
_lowercase = BertTokenizer.from_pretrained("bert-base-uncased" )
# prepare the model inputs
_lowercase = tokenizer.encode("This is sample éàalj'-." )
encoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(_snake_case )) )
_lowercase = torch.tensor(_snake_case ).unsqueeze(0 )
_lowercase = tokenizer.encode("This is sample 3 éàalj'-." )
decoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(_snake_case )) )
_lowercase = torch.tensor(_snake_case ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
_lowercase = encoder_input_ids
_lowercase = decoder_input_ids
_lowercase = _lowercase = None
_lowercase = None
_lowercase = _lowercase = None
_lowercase = _lowercase = None
_lowercase = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
_lowercase = original(_snake_case, _snake_case, _snake_case, _snake_case, _snake_case, _snake_case, _snake_case )[0]
_lowercase = original.generator(_snake_case )
_lowercase = new_model(
_snake_case, _snake_case, _snake_case, _snake_case, _snake_case )[0]
_lowercase = new_model.generator(_snake_case )
_lowercase = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(_snake_case ) )
_lowercase = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print("Maximum absolute difference beween weights: {:.2f}".format(_snake_case ) )
_lowercase = torch.allclose(_snake_case, _snake_case, atol=1e-3 )
if are_identical:
logging.info("all weights are equal up to 1e-3" )
else:
raise ValueError("the weights are different. The new model is likely different from the original one." )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info("saving the model's state dictionary" )
torch.save(
new_model.state_dict(), "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" )
if __name__ == "__main__":
__UpperCamelCase : List[Any] = argparse.ArgumentParser()
parser.add_argument(
"--bertabs_checkpoint_path",
default=None,
type=str,
required=True,
help="Path the official PyTorch dump.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the output PyTorch model.",
)
__UpperCamelCase : List[Any] = parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
) | 227 | 1 |
'''simple docstring'''
from typing import List, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase__ = logging.get_logger(__name__)
lowerCAmelCase__ = {
'''huggingface/time-series-transformer-tourism-monthly''': (
'''https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json'''
),
# See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}
class lowercase_ (lowerCamelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = 'time_series_transformer'
SCREAMING_SNAKE_CASE : List[str] = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
'num_hidden_layers': 'encoder_layers',
}
def __init__( self : Union[str, Any] ,lowercase__ : Optional[int] = None ,lowercase__ : Optional[int] = None ,lowercase__ : str = "student_t" ,lowercase__ : str = "nll" ,lowercase__ : int = 1 ,lowercase__ : List[int] = [1, 2, 3, 4, 5, 6, 7] ,lowercase__ : Optional[Union[str, bool]] = "mean" ,lowercase__ : int = 0 ,lowercase__ : int = 0 ,lowercase__ : int = 0 ,lowercase__ : int = 0 ,lowercase__ : Optional[List[int]] = None ,lowercase__ : Optional[List[int]] = None ,lowercase__ : int = 3_2 ,lowercase__ : int = 3_2 ,lowercase__ : int = 2 ,lowercase__ : int = 2 ,lowercase__ : int = 2 ,lowercase__ : int = 2 ,lowercase__ : bool = True ,lowercase__ : str = "gelu" ,lowercase__ : int = 6_4 ,lowercase__ : float = 0.1 ,lowercase__ : float = 0.1 ,lowercase__ : float = 0.1 ,lowercase__ : float = 0.1 ,lowercase__ : float = 0.1 ,lowercase__ : int = 1_0_0 ,lowercase__ : float = 0.0_2 ,lowercase__ : Any=True ,**lowercase__ : List[str] ,):
# time series specific configuration
__lowercase = prediction_length
__lowercase = context_length or prediction_length
__lowercase = distribution_output
__lowercase = loss
__lowercase = input_size
__lowercase = num_time_features
__lowercase = lags_sequence
__lowercase = scaling
__lowercase = num_dynamic_real_features
__lowercase = num_static_real_features
__lowercase = num_static_categorical_features
if cardinality and num_static_categorical_features > 0:
if len(lowercase__ ) != num_static_categorical_features:
raise ValueError(
'''The cardinality should be a list of the same length as `num_static_categorical_features`''' )
__lowercase = cardinality
else:
__lowercase = [0]
if embedding_dimension and num_static_categorical_features > 0:
if len(lowercase__ ) != num_static_categorical_features:
raise ValueError(
'''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' )
__lowercase = embedding_dimension
else:
__lowercase = [min(5_0 ,(cat + 1) // 2 ) for cat in self.cardinality]
__lowercase = num_parallel_samples
# Transformer architecture configuration
__lowercase = input_size * len(lowercase__ ) + self._number_of_features
__lowercase = d_model
__lowercase = encoder_attention_heads
__lowercase = decoder_attention_heads
__lowercase = encoder_ffn_dim
__lowercase = decoder_ffn_dim
__lowercase = encoder_layers
__lowercase = decoder_layers
__lowercase = dropout
__lowercase = attention_dropout
__lowercase = activation_dropout
__lowercase = encoder_layerdrop
__lowercase = decoder_layerdrop
__lowercase = activation_function
__lowercase = init_std
__lowercase = use_cache
super().__init__(is_encoder_decoder=lowercase__ ,**lowercase__ )
@property
def SCREAMING_SNAKE_CASE ( self : List[str] ):
return (
sum(self.embedding_dimension )
+ self.num_dynamic_real_features
+ self.num_time_features
+ self.num_static_real_features
+ self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
)
| 41 |
from manim import *
class A__ ( UpperCamelCase__ ):
def __UpperCamelCase ( self : Dict ) -> int:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =Rectangle(height=0.5 , width=0.5 )
_SCREAMING_SNAKE_CASE =Rectangle(height=0.25 , width=0.25 )
_SCREAMING_SNAKE_CASE =Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 )
_SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )]
_SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )]
_SCREAMING_SNAKE_CASE =VGroup(*_a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =VGroup(*_a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =VGroup(_a , _a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =Text('''CPU''' , font_size=24 )
_SCREAMING_SNAKE_CASE =Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
cpu.move_to([-2.5, -0.5, 0] )
self.add(_a )
_SCREAMING_SNAKE_CASE =[mem.copy() for i in range(4 )]
_SCREAMING_SNAKE_CASE =VGroup(*_a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =Text('''GPU''' , font_size=24 )
_SCREAMING_SNAKE_CASE =Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
gpu.move_to([-1, -1, 0] )
self.add(_a )
_SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )]
_SCREAMING_SNAKE_CASE =VGroup(*_a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =Text('''Model''' , font_size=24 )
_SCREAMING_SNAKE_CASE =Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
model.move_to([3, -1.0, 0] )
self.add(_a )
_SCREAMING_SNAKE_CASE =[]
_SCREAMING_SNAKE_CASE =[]
_SCREAMING_SNAKE_CASE =[]
for i, rect in enumerate(_a ):
rect.set_stroke(_a )
_SCREAMING_SNAKE_CASE =Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(_a , opacity=0.7 )
if i == 0:
cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_a )
cpu_target.set_x(cpu_target.get_x() + 0.1 )
elif i == 3:
cpu_target.next_to(model_cpu_arr[0] , direction=_a , buff=0.0 )
else:
cpu_target.next_to(model_cpu_arr[i - 1] , direction=_a , buff=0.0 )
self.add(_a )
model_cpu_arr.append(_a )
self.add(*_a , *_a , *_a )
_SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )]
_SCREAMING_SNAKE_CASE =VGroup(*_a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =Text('''Loaded Checkpoint''' , font_size=24 )
_SCREAMING_SNAKE_CASE =Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
checkpoint.move_to([3, 0.5, 0] )
self.add(_a )
_SCREAMING_SNAKE_CASE =[]
_SCREAMING_SNAKE_CASE =[]
for i, rect in enumerate(_a ):
_SCREAMING_SNAKE_CASE =fill.copy().set_fill(_a , opacity=0.7 )
target.move_to(_a )
ckpt_arr.append(_a )
_SCREAMING_SNAKE_CASE =target.copy()
if i < 5:
cpu_target.move_to(cpu_left_col_base[i + 1] )
else:
cpu_target.move_to(cpu_right_col_base[i - 5] )
ckpt_cpu_arr.append(_a )
self.add(*_a , *_a )
_SCREAMING_SNAKE_CASE =Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
_SCREAMING_SNAKE_CASE =MarkupText(
f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , )
key_text.move_to([-5, 2.4, 0] )
self.add(_a , _a )
_SCREAMING_SNAKE_CASE =MarkupText(
f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , )
blue_text.next_to(_a , DOWN * 2.4 , aligned_edge=key_text.get_left() )
self.add(_a )
_SCREAMING_SNAKE_CASE =MarkupText(
f"Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device." , font_size=24 , )
step_a.move_to([2, 2, 0] )
_SCREAMING_SNAKE_CASE =[meta_mem.copy() for i in range(6 )]
_SCREAMING_SNAKE_CASE =[meta_mem.copy() for i in range(6 )]
_SCREAMING_SNAKE_CASE =VGroup(*_a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =VGroup(*_a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =VGroup(_a , _a ).arrange(_a , buff=0 )
_SCREAMING_SNAKE_CASE =Text('''Disk''' , font_size=24 )
_SCREAMING_SNAKE_CASE =Group(_a , _a ).arrange(_a , buff=0.5 , aligned_edge=_a )
disk.move_to([-4.0, -1.25, 0] )
self.play(Write(_a , run_time=3 ) , Write(_a , run_time=1 ) , Create(_a , run_time=1 ) )
_SCREAMING_SNAKE_CASE =[]
for i, rect in enumerate(_a ):
_SCREAMING_SNAKE_CASE =rect.copy()
target.generate_target()
target.target.move_to(disk_left_col_base[i] ).scale(0.5 )
animations.append(MoveToTarget(_a , run_time=1.5 ) )
self.play(*_a )
self.play(FadeOut(_a ) )
_SCREAMING_SNAKE_CASE =MarkupText(f"Then, the checkpoint is removed from memory\nthrough garbage collection." , font_size=24 )
step_a.move_to([2, 2, 0] )
self.play(Write(_a , run_time=3 ) )
self.play(
FadeOut(_a , _a , *_a , *_a ) , )
self.wait() | 691 | 0 |
'''simple docstring'''
from __future__ import annotations
def A_ ( __SCREAMING_SNAKE_CASE : list[int] ) -> int:
"""simple docstring"""
if not nums:
return 0
__A : List[Any] = nums[0]
__A : Union[str, Any] = 0
for num in nums[1:]:
__A , __A : Union[str, Any] = (
max_excluding + num,
max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ),
)
return max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 499 |
'''simple docstring'''
import argparse
import re
import requests
import torch
# git clone https://github.com/salesforce/BLIP.git
from models.blip import blip_decoder
from models.blip_itm import blip_itm
from models.blip_vqa import blip_vqa
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
from transformers import (
BertTokenizer,
BlipConfig,
BlipForConditionalGeneration,
BlipForImageTextRetrieval,
BlipForQuestionAnswering,
)
def A_ ( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] ) -> int:
"""simple docstring"""
__A : Optional[int] = """https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg"""
__A : Tuple = Image.open(requests.get(__SCREAMING_SNAKE_CASE , stream=__SCREAMING_SNAKE_CASE ).raw ).convert("""RGB""" )
__A : Optional[Any] = transforms.Compose(
[
transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ),
transforms.ToTensor(),
transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711) ),
] )
__A : Optional[int] = transform(__SCREAMING_SNAKE_CASE ).unsqueeze(0 ).to(__SCREAMING_SNAKE_CASE )
return image
def A_ ( __SCREAMING_SNAKE_CASE : int ) -> Optional[int]:
"""simple docstring"""
if "visual_encoder" in key:
__A : Dict = re.sub("""visual_encoder*""" , """vision_model.encoder""" , __SCREAMING_SNAKE_CASE )
if "blocks" in key:
__A : Dict = re.sub(R"""blocks""" , """layers""" , __SCREAMING_SNAKE_CASE )
if "attn" in key:
__A : Union[str, Any] = re.sub(R"""attn""" , """self_attn""" , __SCREAMING_SNAKE_CASE )
if "norm1" in key:
__A : str = re.sub(R"""norm1""" , """layer_norm1""" , __SCREAMING_SNAKE_CASE )
if "norm2" in key:
__A : List[Any] = re.sub(R"""norm2""" , """layer_norm2""" , __SCREAMING_SNAKE_CASE )
if "encoder.norm" in key:
__A : Optional[Any] = re.sub(R"""encoder.norm""" , """post_layernorm""" , __SCREAMING_SNAKE_CASE )
if "encoder.patch_embed.proj" in key:
__A : Optional[int] = re.sub(R"""encoder.patch_embed.proj""" , """embeddings.patch_embedding""" , __SCREAMING_SNAKE_CASE )
if "encoder.pos_embed" in key:
__A : Union[str, Any] = re.sub(R"""encoder.pos_embed""" , """embeddings.position_embedding""" , __SCREAMING_SNAKE_CASE )
if "encoder.cls_token" in key:
__A : Tuple = re.sub(R"""encoder.cls_token""" , """embeddings.class_embedding""" , __SCREAMING_SNAKE_CASE )
if "self_attn" in key:
__A : Tuple = re.sub(R"""self_attn.proj""" , """self_attn.projection""" , __SCREAMING_SNAKE_CASE )
return key
@torch.no_grad()
def A_ ( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[str]=None ) -> int:
"""simple docstring"""
if config_path is not None:
__A : Any = BlipConfig.from_pretrained(__SCREAMING_SNAKE_CASE )
else:
__A : List[Any] = BlipConfig(projection_dim=512 , text_config={} , vision_config={} )
__A : List[Any] = BlipForConditionalGeneration(__SCREAMING_SNAKE_CASE ).eval()
__A : List[str] = """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth"""
__A : List[str] = blip_decoder(pretrained=__SCREAMING_SNAKE_CASE , image_size=384 , vit="""base""" )
__A : List[str] = pt_model.eval()
__A : int = pt_model.state_dict()
for key in modified_state_dict.copy():
__A : Tuple = modified_state_dict.pop(__SCREAMING_SNAKE_CASE )
__A : Dict = rename_key(__SCREAMING_SNAKE_CASE )
__A : Tuple = value
hf_model.load_state_dict(__SCREAMING_SNAKE_CASE )
__A : List[Any] = 384
__A : Dict = load_demo_image(image_size=__SCREAMING_SNAKE_CASE , device="""cpu""" )
__A : Dict = BertTokenizer.from_pretrained("""bert-base-uncased""" )
__A : Optional[Any] = tokenizer(["""a picture of"""] ).input_ids
__A : int = hf_model.generate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
assert out[0].tolist() == [3_0522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]
__A : str = hf_model.generate(__SCREAMING_SNAKE_CASE )
assert out[0].tolist() == [3_0522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]
if pytorch_dump_folder_path is not None:
hf_model.save_pretrained(__SCREAMING_SNAKE_CASE )
# model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'
__A : List[Any] = (
"""https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth"""
)
__A : List[Any] = blip_vqa(pretrained=__SCREAMING_SNAKE_CASE , image_size=__SCREAMING_SNAKE_CASE , vit="""base""" )
vqa_model.eval()
__A : List[Any] = vqa_model.state_dict()
for key in modified_state_dict.copy():
__A : List[Any] = modified_state_dict.pop(__SCREAMING_SNAKE_CASE )
__A : int = rename_key(__SCREAMING_SNAKE_CASE )
__A : Union[str, Any] = value
__A : Any = BlipForQuestionAnswering(__SCREAMING_SNAKE_CASE )
hf_vqa_model.load_state_dict(__SCREAMING_SNAKE_CASE )
__A : Tuple = ["""How many dogs are in this image?"""]
__A : Union[str, Any] = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_ids
__A : List[str] = hf_vqa_model.generate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
print(tokenizer.decode(answer[0] ) )
assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]"
if pytorch_dump_folder_path is not None:
hf_vqa_model.save_pretrained(pytorch_dump_folder_path + """_vqa""" )
__A : str = """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth"""
__A : List[str] = blip_itm(pretrained=__SCREAMING_SNAKE_CASE , image_size=__SCREAMING_SNAKE_CASE , vit="""base""" )
itm_model.eval()
__A : List[str] = itm_model.state_dict()
for key in modified_state_dict.copy():
__A : Optional[Any] = modified_state_dict.pop(__SCREAMING_SNAKE_CASE )
__A : str = rename_key(__SCREAMING_SNAKE_CASE )
__A : Any = value
__A : List[Any] = BlipForImageTextRetrieval(__SCREAMING_SNAKE_CASE )
__A : Tuple = ["""A picture of a woman with a dog sitting in a beach"""]
__A : List[str] = tokenizer(
__SCREAMING_SNAKE_CASE , return_tensors="""pt""" , padding="""max_length""" , truncation=__SCREAMING_SNAKE_CASE , max_length=35 , ).input_ids
hf_itm_model.load_state_dict(__SCREAMING_SNAKE_CASE )
hf_itm_model.eval()
__A : Any = hf_itm_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_itm_head=__SCREAMING_SNAKE_CASE )
__A : Optional[Any] = hf_itm_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_itm_head=__SCREAMING_SNAKE_CASE )
assert out[0].item() == 0.2_110_687_494_277_954
assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45_698_845_386_505_127
if pytorch_dump_folder_path is not None:
hf_itm_model.save_pretrained(pytorch_dump_folder_path + """_itm""" )
if __name__ == "__main__":
A__ : Tuple =argparse.ArgumentParser()
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
A__ : Any =parser.parse_args()
convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
| 499 | 1 |
import inspect
import unittest
from transformers import ViTConfig
from transformers.testing_utils import (
require_accelerate,
require_torch,
require_torch_gpu,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class _a :
"""simple docstring"""
def __init__( self : Optional[int] , UpperCAmelCase : Any , UpperCAmelCase : Any=13 , UpperCAmelCase : Any=30 , UpperCAmelCase : int=2 , UpperCAmelCase : Union[str, Any]=3 , UpperCAmelCase : List[Any]=True , UpperCAmelCase : str=True , UpperCAmelCase : Dict=32 , UpperCAmelCase : str=5 , UpperCAmelCase : Any=4 , UpperCAmelCase : str=37 , UpperCAmelCase : List[Any]="gelu" , UpperCAmelCase : List[Any]=0.1 , UpperCAmelCase : int=0.1 , UpperCAmelCase : Optional[Any]=10 , UpperCAmelCase : List[Any]=0.02 , UpperCAmelCase : Union[str, Any]=None , UpperCAmelCase : Tuple=2 , ):
A_ = parent
A_ = batch_size
A_ = image_size
A_ = patch_size
A_ = num_channels
A_ = is_training
A_ = use_labels
A_ = hidden_size
A_ = num_hidden_layers
A_ = num_attention_heads
A_ = intermediate_size
A_ = hidden_act
A_ = hidden_dropout_prob
A_ = attention_probs_dropout_prob
A_ = type_sequence_label_size
A_ = initializer_range
A_ = scope
A_ = encoder_stride
# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
A_ = (image_size // patch_size) ** 2
A_ = num_patches + 1
def __A ( self : Union[str, Any] ):
A_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
A_ = None
if self.use_labels:
A_ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
A_ = self.get_config()
return config, pixel_values, labels
def __A ( self : Optional[Any] ):
return ViTConfig(
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=UpperCAmelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def __A ( self : Tuple , UpperCAmelCase : str , UpperCAmelCase : Any , UpperCAmelCase : Any ):
A_ = ViTModel(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
A_ = model(UpperCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __A ( self : Tuple , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Any , UpperCAmelCase : Optional[Any] ):
A_ = ViTForMaskedImageModeling(config=UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
A_ = model(UpperCAmelCase )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
A_ = 1
A_ = ViTForMaskedImageModeling(UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
A_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
A_ = model(UpperCAmelCase )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def __A ( self : str , UpperCAmelCase : int , UpperCAmelCase : Any , UpperCAmelCase : Any ):
A_ = self.type_sequence_label_size
A_ = ViTForImageClassification(UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
A_ = model(UpperCAmelCase , labels=UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
A_ = 1
A_ = ViTForImageClassification(UpperCAmelCase )
model.to(UpperCAmelCase )
model.eval()
A_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
A_ = model(UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def __A ( self : Optional[Any] ):
A_ = self.prepare_config_and_inputs()
(
(
A_
) , (
A_
) , (
A_
) ,
) = config_and_inputs
A_ = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class _a ( snake_case_ , snake_case_ , unittest.TestCase ):
"""simple docstring"""
_lowerCamelCase : List[str] = (
(
ViTModel,
ViTForImageClassification,
ViTForMaskedImageModeling,
)
if is_torch_available()
else ()
)
_lowerCamelCase : Optional[Any] = (
{'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
if is_torch_available()
else {}
)
_lowerCamelCase : List[Any] = True
_lowerCamelCase : List[str] = False
_lowerCamelCase : str = False
_lowerCamelCase : Tuple = False
def __A ( self : Optional[Any] ):
A_ = ViTModelTester(self )
A_ = ConfigTester(self , config_class=UpperCAmelCase , has_text_modality=UpperCAmelCase , hidden_size=37 )
def __A ( self : Optional[Any] ):
self.config_tester.run_common_tests()
@unittest.skip(reason="ViT does not use inputs_embeds" )
def __A ( self : Tuple ):
pass
def __A ( self : int ):
A_ , A_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
A_ = model_class(UpperCAmelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
A_ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(UpperCAmelCase , nn.Linear ) )
def __A ( self : Tuple ):
A_ , A_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
A_ = model_class(UpperCAmelCase )
A_ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
A_ = [*signature.parameters.keys()]
A_ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , UpperCAmelCase )
def __A ( self : Tuple ):
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase )
def __A ( self : int ):
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase )
def __A ( self : str ):
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase )
@slow
def __A ( self : Tuple ):
for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A_ = ViTModel.from_pretrained(UpperCAmelCase )
self.assertIsNotNone(UpperCAmelCase )
def __snake_case ( ):
"""simple docstring"""
A_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class _a ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def __A ( self : List[Any] ):
return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None
@slow
def __A ( self : str ):
A_ = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(UpperCAmelCase )
A_ = self.default_image_processor
A_ = prepare_img()
A_ = image_processor(images=UpperCAmelCase , return_tensors="pt" ).to(UpperCAmelCase )
# forward pass
with torch.no_grad():
A_ = model(**UpperCAmelCase )
# verify the logits
A_ = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , UpperCAmelCase )
A_ = torch.tensor([-0.2_744, 0.8_215, -0.0_836] ).to(UpperCAmelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase , atol=1E-4 ) )
@slow
def __A ( self : Any ):
# ViT models have an `interpolate_pos_encoding` argument in their forward method,
# allowing to interpolate the pre-trained position embeddings in order to use
# the model on higher resolutions. The DINO model by Facebook AI leverages this
# to visualize self-attention on higher resolution images.
A_ = ViTModel.from_pretrained("facebook/dino-vits8" ).to(UpperCAmelCase )
A_ = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 )
A_ = prepare_img()
A_ = image_processor(images=UpperCAmelCase , return_tensors="pt" )
A_ = inputs.pixel_values.to(UpperCAmelCase )
# forward pass
with torch.no_grad():
A_ = model(UpperCAmelCase , interpolate_pos_encoding=UpperCAmelCase )
# verify the logits
A_ = torch.Size((1, 3601, 384) )
self.assertEqual(outputs.last_hidden_state.shape , UpperCAmelCase )
A_ = torch.tensor(
[[4.2_340, 4.3_906, -6.6_692], [4.5_463, 1.8_928, -6.7_257], [4.4_429, 0.8_496, -5.8_585]] ).to(UpperCAmelCase )
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase , atol=1E-4 ) )
@slow
@require_accelerate
@require_torch_gpu
def __A ( self : Optional[int] ):
A_ = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" )
A_ = self.default_image_processor
A_ = prepare_img()
A_ = image_processor(images=UpperCAmelCase , return_tensors="pt" )
A_ = inputs.pixel_values.to(UpperCAmelCase )
# forward pass to make sure inference works in fp16
with torch.no_grad():
A_ = model(UpperCAmelCase ) | 86 |
"""simple docstring"""
import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Callable, Dict, List, Tuple
import timm
import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs
from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.utils import logging
logging.set_verbosity_info()
a__ : int = logging.get_logger()
@dataclass
class __magic_name__ :
UpperCamelCase : nn.Module
UpperCamelCase : List[nn.Module] = field(default_factory=_UpperCamelCase )
UpperCamelCase : list = field(default_factory=_UpperCamelCase )
def _lowerCamelCase ( self , __magic_name__ , __magic_name__ , __magic_name__ ):
"""simple docstring"""
_lowerCAmelCase = len(list(m.modules() ) ) == 1 or isinstance(__magic_name__ , nn.Convad ) or isinstance(__magic_name__ , nn.BatchNormad )
if has_not_submodules:
self.traced.append(__magic_name__ )
def __call__( self , __magic_name__ ):
"""simple docstring"""
for m in self.module.modules():
self.handles.append(m.register_forward_hook(self._forward_hook ) )
self.module(__magic_name__ )
[x.remove() for x in self.handles]
return self
@property
def _lowerCamelCase ( self ):
"""simple docstring"""
return list(filter(lambda __magic_name__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) )
@dataclass
class __magic_name__ :
UpperCamelCase : nn.Module
UpperCamelCase : nn.Module
UpperCamelCase : int = 1
UpperCamelCase : List = field(default_factory=_UpperCamelCase )
UpperCamelCase : List = field(default_factory=_UpperCamelCase )
UpperCamelCase : bool = True
def __call__( self , __magic_name__ ):
"""simple docstring"""
_lowerCAmelCase = Tracker(self.dest )(__magic_name__ ).parametrized
_lowerCAmelCase = Tracker(self.src )(__magic_name__ ).parametrized
_lowerCAmelCase = list(filter(lambda __magic_name__ : type(__magic_name__ ) not in self.src_skip , __magic_name__ ) )
_lowerCAmelCase = list(filter(lambda __magic_name__ : type(__magic_name__ ) not in self.dest_skip , __magic_name__ ) )
if len(__magic_name__ ) != len(__magic_name__ ) and self.raise_if_mismatch:
raise Exception(
F'''Numbers of operations are different. Source module has {len(__magic_name__ )} operations while'''
F''' destination module has {len(__magic_name__ )}.''' )
for dest_m, src_m in zip(__magic_name__ , __magic_name__ ):
dest_m.load_state_dict(src_m.state_dict() )
if self.verbose == 1:
print(F'''Transfered from={src_m} to={dest_m}''' )
class __magic_name__ ( nn.Module ):
def __init__( self , __magic_name__ ):
"""simple docstring"""
super().__init__()
_lowerCAmelCase = []
# - get the stem
feature_blocks.append(('conv1', model.stem) )
# - get all the feature blocks
for k, v in model.trunk_output.named_children():
assert k.startswith('block' ), F'''Unexpected layer name {k}'''
_lowerCAmelCase = len(__magic_name__ ) + 1
feature_blocks.append((F'''res{block_index}''', v) )
_lowerCAmelCase = nn.ModuleDict(__magic_name__ )
def _lowerCamelCase ( self , __magic_name__ ):
"""simple docstring"""
return get_trunk_forward_outputs(
__magic_name__ , out_feat_keys=__magic_name__ , feature_blocks=self._feature_blocks , )
class __magic_name__ ( _UpperCamelCase ):
def _lowerCamelCase ( self , __magic_name__ ):
"""simple docstring"""
_lowerCAmelCase = x.split('-' )
return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] )
def __getitem__( self , __magic_name__ ):
"""simple docstring"""
if x not in self:
_lowerCAmelCase = self.convert_name_to_timm(__magic_name__ )
_lowerCAmelCase = partial(lambda: (timm.create_model(__magic_name__ , pretrained=__magic_name__ ).eval(), None) )
else:
_lowerCAmelCase = super().__getitem__(__magic_name__ )
return val
class __magic_name__ ( _UpperCamelCase ):
def __getitem__( self , __magic_name__ ):
"""simple docstring"""
if "seer" in x and "in1k" not in x:
_lowerCAmelCase = RegNetModel
else:
_lowerCAmelCase = RegNetForImageClassification
return val
def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ):
"""simple docstring"""
for from_key, to_key in keys:
_lowerCAmelCase = from_state_dict[from_key].clone()
print(F'''Copied key={from_key} to={to_key}''' )
return to_state_dict
def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = True, ):
"""simple docstring"""
print(F'''Converting {name}...''' )
with torch.no_grad():
_lowerCAmelCase , _lowerCAmelCase = from_model_func()
_lowerCAmelCase = our_model_func(__lowerCamelCase ).eval()
_lowerCAmelCase = ModuleTransfer(src=__lowerCamelCase, dest=__lowerCamelCase, raise_if_mismatch=__lowerCamelCase )
_lowerCAmelCase = torch.randn((1, 3, 2_2_4, 2_2_4) )
module_transfer(__lowerCamelCase )
if from_state_dict is not None:
_lowerCAmelCase = []
# for seer - in1k finetuned we have to manually copy the head
if "seer" in name and "in1k" in name:
_lowerCAmelCase = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')]
_lowerCAmelCase = manually_copy_vissl_head(__lowerCamelCase, our_model.state_dict(), __lowerCamelCase )
our_model.load_state_dict(__lowerCamelCase )
_lowerCAmelCase = our_model(__lowerCamelCase, output_hidden_states=__lowerCamelCase )
_lowerCAmelCase = (
our_outputs.logits if isinstance(__lowerCamelCase, __lowerCamelCase ) else our_outputs.last_hidden_state
)
_lowerCAmelCase = from_model(__lowerCamelCase )
_lowerCAmelCase = from_output[-1] if type(__lowerCamelCase ) is list else from_output
# now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
if "seer" in name and "in1k" in name:
_lowerCAmelCase = our_outputs.hidden_states[-1]
assert torch.allclose(__lowerCamelCase, __lowerCamelCase ), "The model logits don't match the original one."
if push_to_hub:
our_model.push_to_hub(
repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=__lowerCamelCase, )
_lowerCAmelCase = 2_2_4 if 'seer' not in name else 3_8_4
# we can use the convnext one
_lowerCAmelCase = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=__lowerCamelCase )
image_processor.push_to_hub(
repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=__lowerCamelCase, )
print(F'''Pushed {name}''' )
def A__ ( __lowerCamelCase, __lowerCamelCase = None, __lowerCamelCase = True ):
"""simple docstring"""
_lowerCAmelCase = 'imagenet-1k-id2label.json'
_lowerCAmelCase = 1_0_0_0
_lowerCAmelCase = (1, num_labels)
_lowerCAmelCase = 'huggingface/label-files'
_lowerCAmelCase = num_labels
_lowerCAmelCase = json.load(open(cached_download(hf_hub_url(__lowerCamelCase, __lowerCamelCase, repo_type='dataset' ) ), 'r' ) )
_lowerCAmelCase = {int(__lowerCamelCase ): v for k, v in idalabel.items()}
_lowerCAmelCase = idalabel
_lowerCAmelCase = {v: k for k, v in idalabel.items()}
_lowerCAmelCase = partial(__lowerCamelCase, num_labels=__lowerCamelCase, idalabel=__lowerCamelCase, labelaid=__lowerCamelCase )
_lowerCAmelCase = {
'regnet-x-002': ImageNetPreTrainedConfig(
depths=[1, 1, 4, 7], hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8], groups_width=8, layer_type='x' ),
'regnet-x-004': ImageNetPreTrainedConfig(
depths=[1, 2, 7, 1_2], hidden_sizes=[3_2, 6_4, 1_6_0, 3_8_4], groups_width=1_6, layer_type='x' ),
'regnet-x-006': ImageNetPreTrainedConfig(
depths=[1, 3, 5, 7], hidden_sizes=[4_8, 9_6, 2_4_0, 5_2_8], groups_width=2_4, layer_type='x' ),
'regnet-x-008': ImageNetPreTrainedConfig(
depths=[1, 3, 7, 5], hidden_sizes=[6_4, 1_2_8, 2_8_8, 6_7_2], groups_width=1_6, layer_type='x' ),
'regnet-x-016': ImageNetPreTrainedConfig(
depths=[2, 4, 1_0, 2], hidden_sizes=[7_2, 1_6_8, 4_0_8, 9_1_2], groups_width=2_4, layer_type='x' ),
'regnet-x-032': ImageNetPreTrainedConfig(
depths=[2, 6, 1_5, 2], hidden_sizes=[9_6, 1_9_2, 4_3_2, 1_0_0_8], groups_width=4_8, layer_type='x' ),
'regnet-x-040': ImageNetPreTrainedConfig(
depths=[2, 5, 1_4, 2], hidden_sizes=[8_0, 2_4_0, 5_6_0, 1_3_6_0], groups_width=4_0, layer_type='x' ),
'regnet-x-064': ImageNetPreTrainedConfig(
depths=[2, 4, 1_0, 1], hidden_sizes=[1_6_8, 3_9_2, 7_8_4, 1_6_2_4], groups_width=5_6, layer_type='x' ),
'regnet-x-080': ImageNetPreTrainedConfig(
depths=[2, 5, 1_5, 1], hidden_sizes=[8_0, 2_4_0, 7_2_0, 1_9_2_0], groups_width=1_2_0, layer_type='x' ),
'regnet-x-120': ImageNetPreTrainedConfig(
depths=[2, 5, 1_1, 1], hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0], groups_width=1_1_2, layer_type='x' ),
'regnet-x-160': ImageNetPreTrainedConfig(
depths=[2, 6, 1_3, 1], hidden_sizes=[2_5_6, 5_1_2, 8_9_6, 2_0_4_8], groups_width=1_2_8, layer_type='x' ),
'regnet-x-320': ImageNetPreTrainedConfig(
depths=[2, 7, 1_3, 1], hidden_sizes=[3_3_6, 6_7_2, 1_3_4_4, 2_5_2_0], groups_width=1_6_8, layer_type='x' ),
# y variant
'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8], groups_width=8 ),
'regnet-y-004': ImageNetPreTrainedConfig(
depths=[1, 3, 6, 6], hidden_sizes=[4_8, 1_0_4, 2_0_8, 4_4_0], groups_width=8 ),
'regnet-y-006': ImageNetPreTrainedConfig(
depths=[1, 3, 7, 4], hidden_sizes=[4_8, 1_1_2, 2_5_6, 6_0_8], groups_width=1_6 ),
'regnet-y-008': ImageNetPreTrainedConfig(
depths=[1, 3, 8, 2], hidden_sizes=[6_4, 1_2_8, 3_2_0, 7_6_8], groups_width=1_6 ),
'regnet-y-016': ImageNetPreTrainedConfig(
depths=[2, 6, 1_7, 2], hidden_sizes=[4_8, 1_2_0, 3_3_6, 8_8_8], groups_width=2_4 ),
'regnet-y-032': ImageNetPreTrainedConfig(
depths=[2, 5, 1_3, 1], hidden_sizes=[7_2, 2_1_6, 5_7_6, 1_5_1_2], groups_width=2_4 ),
'regnet-y-040': ImageNetPreTrainedConfig(
depths=[2, 6, 1_2, 2], hidden_sizes=[1_2_8, 1_9_2, 5_1_2, 1_0_8_8], groups_width=6_4 ),
'regnet-y-064': ImageNetPreTrainedConfig(
depths=[2, 7, 1_4, 2], hidden_sizes=[1_4_4, 2_8_8, 5_7_6, 1_2_9_6], groups_width=7_2 ),
'regnet-y-080': ImageNetPreTrainedConfig(
depths=[2, 4, 1_0, 1], hidden_sizes=[1_6_8, 4_4_8, 8_9_6, 2_0_1_6], groups_width=5_6 ),
'regnet-y-120': ImageNetPreTrainedConfig(
depths=[2, 5, 1_1, 1], hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0], groups_width=1_1_2 ),
'regnet-y-160': ImageNetPreTrainedConfig(
depths=[2, 4, 1_1, 1], hidden_sizes=[2_2_4, 4_4_8, 1_2_3_2, 3_0_2_4], groups_width=1_1_2 ),
'regnet-y-320': ImageNetPreTrainedConfig(
depths=[2, 5, 1_2, 1], hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2], groups_width=2_3_2 ),
# models created by SEER -> https://arxiv.org/abs/2202.08360
'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 1_2, 1], hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2], groups_width=2_3_2 ),
'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 1_2, 1], hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0], groups_width=3_2_8 ),
'regnet-y-1280-seer': RegNetConfig(
depths=[2, 7, 1_7, 1], hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2], groups_width=2_6_4 ),
'regnet-y-2560-seer': RegNetConfig(
depths=[3, 7, 1_6, 1], hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8], groups_width=6_4_0 ),
'regnet-y-10b-seer': ImageNetPreTrainedConfig(
depths=[2, 7, 1_7, 1], hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0], groups_width=1_0_1_0 ),
# finetuned on imagenet
'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig(
depths=[2, 5, 1_2, 1], hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2], groups_width=2_3_2 ),
'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig(
depths=[2, 5, 1_2, 1], hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0], groups_width=3_2_8 ),
'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig(
depths=[2, 7, 1_7, 1], hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2], groups_width=2_6_4 ),
'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig(
depths=[3, 7, 1_6, 1], hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8], groups_width=6_4_0 ),
'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig(
depths=[2, 7, 1_7, 1], hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0], groups_width=1_0_1_0 ),
}
_lowerCAmelCase = NameToOurModelFuncMap()
_lowerCAmelCase = NameToFromModelFuncMap()
# add seer weights logic
def load_using_classy_vision(__lowerCamelCase, __lowerCamelCase ) -> Tuple[nn.Module, Dict]:
_lowerCAmelCase = torch.hub.load_state_dict_from_url(__lowerCamelCase, model_dir=str(__lowerCamelCase ), map_location='cpu' )
_lowerCAmelCase = model_func()
# check if we have a head, if yes add it
_lowerCAmelCase = files['classy_state_dict']['base_model']['model']
_lowerCAmelCase = model_state_dict['trunk']
model.load_state_dict(__lowerCamelCase )
return model.eval(), model_state_dict["heads"]
# pretrained
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), )
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), )
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), )
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=2_7, group_width=1_0_1_0, w_a=1_7_4_4, w_a=620.83, w_m=2.52 ) ) ), )
# IN1K finetuned
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), )
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), )
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), )
_lowerCAmelCase = partial(
__lowerCamelCase, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=2_7, group_width=1_0_1_0, w_a=1_7_4_4, w_a=620.83, w_m=2.52 ) ) ), )
if model_name:
convert_weight_and_push(
__lowerCamelCase, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], __lowerCamelCase, __lowerCamelCase, )
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(
__lowerCamelCase, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, )
return config, expected_shape
if __name__ == "__main__":
a__ : List[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default=None,
type=str,
help=(
"""The name of the model you wish to convert, it must be one of the supported regnet* architecture,"""
""" currently: regnetx-*, regnety-*. If `None`, all of them will the converted."""
),
)
parser.add_argument(
"""--pytorch_dump_folder_path""",
default=None,
type=Path,
required=True,
help="""Path to the output PyTorch model directory.""",
)
parser.add_argument(
"""--push_to_hub""",
default=True,
type=bool,
required=False,
help="""If True, push model and image processor to the hub.""",
)
a__ : Optional[int] = parser.parse_args()
a__ : Path = args.pytorch_dump_folder_path
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 589 | 0 |
import os
from itertools import chain
from random import randrange, shuffle
import pytest
from .sola import PokerHand
SCREAMING_SNAKE_CASE__ = (
"""4S 3H 2C 7S 5H""",
"""9D 8H 2C 6S 7H""",
"""2D 6D 9D TH 7D""",
"""TC 8C 2S JH 6C""",
"""JH 8S TH AH QH""",
"""TS KS 5S 9S AC""",
"""KD 6S 9D TH AD""",
"""KS 8D 4D 9S 4S""", # pair
"""8C 4S KH JS 4D""", # pair
"""QH 8H KD JH 8S""", # pair
"""KC 4H KS 2H 8D""", # pair
"""KD 4S KC 3H 8S""", # pair
"""AH 8S AS KC JH""", # pair
"""3H 4C 4H 3S 2H""", # 2 pairs
"""5S 5D 2C KH KH""", # 2 pairs
"""3C KH 5D 5S KH""", # 2 pairs
"""AS 3C KH AD KH""", # 2 pairs
"""7C 7S 3S 7H 5S""", # 3 of a kind
"""7C 7S KH 2H 7H""", # 3 of a kind
"""AC KH QH AH AS""", # 3 of a kind
"""2H 4D 3C AS 5S""", # straight (low ace)
"""3C 5C 4C 2C 6H""", # straight
"""6S 8S 7S 5H 9H""", # straight
"""JS QS 9H TS KH""", # straight
"""QC KH TS JS AH""", # straight (high ace)
"""8C 9C 5C 3C TC""", # flush
"""3S 8S 9S 5S KS""", # flush
"""4C 5C 9C 8C KC""", # flush
"""JH 8H AH KH QH""", # flush
"""3D 2H 3H 2C 2D""", # full house
"""2H 2C 3S 3H 3D""", # full house
"""KH KC 3S 3H 3D""", # full house
"""JC 6H JS JD JH""", # 4 of a kind
"""JC 7H JS JD JH""", # 4 of a kind
"""JC KH JS JD JH""", # 4 of a kind
"""2S AS 4S 5S 3S""", # straight flush (low ace)
"""2D 6D 3D 4D 5D""", # straight flush
"""5C 6C 3C 7C 4C""", # straight flush
"""JH 9H TH KH QH""", # straight flush
"""JH AH TH KH QH""", # royal flush (high ace straight flush)
)
SCREAMING_SNAKE_CASE__ = (
("""2H 3H 4H 5H 6H""", """KS AS TS QS JS""", """Loss"""),
("""2H 3H 4H 5H 6H""", """AS AD AC AH JD""", """Win"""),
("""AS AH 2H AD AC""", """JS JD JC JH 3D""", """Win"""),
("""2S AH 2H AS AC""", """JS JD JC JH AD""", """Loss"""),
("""2S AH 2H AS AC""", """2H 3H 5H 6H 7H""", """Win"""),
("""AS 3S 4S 8S 2S""", """2H 3H 5H 6H 7H""", """Win"""),
("""2H 3H 5H 6H 7H""", """2S 3H 4H 5S 6C""", """Win"""),
("""2S 3H 4H 5S 6C""", """3D 4C 5H 6H 2S""", """Tie"""),
("""2S 3H 4H 5S 6C""", """AH AC 5H 6H AS""", """Win"""),
("""2S 2H 4H 5S 4C""", """AH AC 5H 6H AS""", """Loss"""),
("""2S 2H 4H 5S 4C""", """AH AC 5H 6H 7S""", """Win"""),
("""6S AD 7H 4S AS""", """AH AC 5H 6H 7S""", """Loss"""),
("""2S AH 4H 5S KC""", """AH AC 5H 6H 7S""", """Loss"""),
("""2S 3H 6H 7S 9C""", """7H 3C TH 6H 9S""", """Loss"""),
("""4S 5H 6H TS AC""", """3S 5H 6H TS AC""", """Win"""),
("""2S AH 4H 5S 6C""", """AD 4C 5H 6H 2C""", """Tie"""),
("""AS AH 3H AD AC""", """AS AH 2H AD AC""", """Win"""),
("""AH AC 5H 5C QS""", """AH AC 5H 5C KS""", """Loss"""),
("""AH AC 5H 5C QS""", """KH KC 5H 5C QS""", """Win"""),
("""7C 7S KH 2H 7H""", """3C 3S AH 2H 3H""", """Win"""),
("""3C 3S AH 2H 3H""", """7C 7S KH 2H 7H""", """Loss"""),
("""6H 5H 4H 3H 2H""", """5H 4H 3H 2H AH""", """Win"""),
("""5H 4H 3H 2H AH""", """5H 4H 3H 2H AH""", """Tie"""),
("""5H 4H 3H 2H AH""", """6H 5H 4H 3H 2H""", """Loss"""),
("""AH AD KS KC AC""", """AH KD KH AC KC""", """Win"""),
("""2H 4D 3C AS 5S""", """2H 4D 3C 6S 5S""", """Loss"""),
("""2H 3S 3C 3H 2S""", """3S 3C 2S 2H 2D""", """Win"""),
("""4D 6D 5D 2D JH""", """3S 8S 3H TC KH""", """Loss"""),
("""4S 6C 8S 3S 7S""", """AD KS 2D 7D 7C""", """Loss"""),
("""6S 4C 7H 8C 3H""", """5H JC AH 9D 9C""", """Loss"""),
("""9D 9H JH TC QH""", """3C 2S JS 5C 7H""", """Win"""),
("""2H TC 8S AD 9S""", """4H TS 7H 2C 5C""", """Win"""),
("""9D 3S 2C 7S 7C""", """JC TD 3C TC 9H""", """Loss"""),
)
SCREAMING_SNAKE_CASE__ = (
("""2H 3H 4H 5H 6H""", True),
("""AS AH 2H AD AC""", False),
("""2H 3H 5H 6H 7H""", True),
("""KS AS TS QS JS""", True),
("""8H 9H QS JS TH""", False),
("""AS 3S 4S 8S 2S""", True),
)
SCREAMING_SNAKE_CASE__ = (
("""2H 3H 4H 5H 6H""", True),
("""AS AH 2H AD AC""", False),
("""2H 3H 5H 6H 7H""", False),
("""KS AS TS QS JS""", True),
("""8H 9H QS JS TH""", True),
)
SCREAMING_SNAKE_CASE__ = (
("""2H 4D 3C AS 5S""", True, [5, 4, 3, 2, 1_4]),
("""2H 5D 3C AS 5S""", False, [1_4, 5, 5, 3, 2]),
("""JH QD KC AS TS""", False, [1_4, 1_3, 1_2, 1_1, 1_0]),
("""9D 3S 2C 7S 7C""", False, [9, 7, 7, 3, 2]),
)
SCREAMING_SNAKE_CASE__ = (
("""JH AH TH KH QH""", 0),
("""JH 9H TH KH QH""", 0),
("""JC KH JS JD JH""", 7),
("""KH KC 3S 3H 3D""", 6),
("""8C 9C 5C 3C TC""", 0),
("""JS QS 9H TS KH""", 0),
("""7C 7S KH 2H 7H""", 3),
("""3C KH 5D 5S KH""", 2),
("""QH 8H KD JH 8S""", 1),
("""2D 6D 9D TH 7D""", 0),
)
SCREAMING_SNAKE_CASE__ = (
("""JH AH TH KH QH""", 2_3),
("""JH 9H TH KH QH""", 2_2),
("""JC KH JS JD JH""", 2_1),
("""KH KC 3S 3H 3D""", 2_0),
("""8C 9C 5C 3C TC""", 1_9),
("""JS QS 9H TS KH""", 1_8),
("""7C 7S KH 2H 7H""", 1_7),
("""3C KH 5D 5S KH""", 1_6),
("""QH 8H KD JH 8S""", 1_5),
("""2D 6D 9D TH 7D""", 1_4),
)
def SCREAMING_SNAKE_CASE_ ( ):
'''simple docstring'''
lowercase_ , lowercase_ = randrange(len(__lowerCamelCase ) ), randrange(len(__lowerCamelCase ) )
lowercase_ = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)]
lowercase_ , lowercase_ = SORTED_HANDS[play], SORTED_HANDS[oppo]
return hand, other, expected
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: int = 100 ):
'''simple docstring'''
return (generate_random_hand() for _ in range(__lowerCamelCase ))
@pytest.mark.parametrize("hand, expected" , __lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: int , __lowerCamelCase: List[Any] ):
'''simple docstring'''
assert PokerHand(__lowerCamelCase )._is_flush() == expected
@pytest.mark.parametrize("hand, expected" , __lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: int , __lowerCamelCase: Union[str, Any] ):
'''simple docstring'''
assert PokerHand(__lowerCamelCase )._is_straight() == expected
@pytest.mark.parametrize("hand, expected, card_values" , __lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: Union[str, Any] , __lowerCamelCase: List[Any] , __lowerCamelCase: Tuple ):
'''simple docstring'''
lowercase_ = PokerHand(__lowerCamelCase )
assert player._is_five_high_straight() == expected
assert player._card_values == card_values
@pytest.mark.parametrize("hand, expected" , __lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: int , __lowerCamelCase: Any ):
'''simple docstring'''
assert PokerHand(__lowerCamelCase )._is_same_kind() == expected
@pytest.mark.parametrize("hand, expected" , __lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: Optional[Any] , __lowerCamelCase: Any ):
'''simple docstring'''
assert PokerHand(__lowerCamelCase )._hand_type == expected
@pytest.mark.parametrize("hand, other, expected" , __lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: Optional[int] , __lowerCamelCase: str , __lowerCamelCase: str ):
'''simple docstring'''
assert PokerHand(__lowerCamelCase ).compare_with(PokerHand(__lowerCamelCase ) ) == expected
@pytest.mark.parametrize("hand, other, expected" , generate_random_hands() )
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: str , __lowerCamelCase: List[Any] , __lowerCamelCase: Optional[int] ):
'''simple docstring'''
assert PokerHand(__lowerCamelCase ).compare_with(PokerHand(__lowerCamelCase ) ) == expected
def SCREAMING_SNAKE_CASE_ ( ):
'''simple docstring'''
lowercase_ = [PokerHand(__lowerCamelCase ) for hand in SORTED_HANDS]
lowercase_ = poker_hands.copy()
shuffle(__lowerCamelCase )
lowercase_ = chain(sorted(__lowerCamelCase ) )
for index, hand in enumerate(__lowerCamelCase ):
assert hand == poker_hands[index]
def SCREAMING_SNAKE_CASE_ ( ):
'''simple docstring'''
lowercase_ = [PokerHand("2D AC 3H 4H 5S" ), PokerHand("2S 3H 4H 5S 6C" )]
pokerhands.sort(reverse=__lowerCamelCase )
assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C"
def SCREAMING_SNAKE_CASE_ ( ):
'''simple docstring'''
lowercase_ = PokerHand("2C 4S AS 3D 5C" )
lowercase_ = True
lowercase_ = [5, 4, 3, 2, 14]
for _ in range(10 ):
assert pokerhand._is_five_high_straight() == expected
assert pokerhand._card_values == expected_card_values
def SCREAMING_SNAKE_CASE_ ( ):
'''simple docstring'''
lowercase_ = 0
lowercase_ = os.path.abspath(os.path.dirname(__lowerCamelCase ) )
lowercase_ = os.path.join(__lowerCamelCase , "poker_hands.txt" )
with open(__lowerCamelCase ) as file_hand:
for line in file_hand:
lowercase_ = line[:14].strip()
lowercase_ = line[15:].strip()
lowercase_ , lowercase_ = PokerHand(__lowerCamelCase ), PokerHand(__lowerCamelCase )
lowercase_ = player.compare_with(__lowerCamelCase )
if output == "Win":
answer += 1
assert answer == 376
| 601 |
from __future__ import annotations
from cmath import sqrt
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: int , __lowerCamelCase: int , __lowerCamelCase: int ):
'''simple docstring'''
if a == 0:
raise ValueError("Coefficient 'a' must not be zero." )
lowercase_ = b * b - 4 * a * c
lowercase_ = (-b + sqrt(__lowerCamelCase )) / (2 * a)
lowercase_ = (-b - sqrt(__lowerCamelCase )) / (2 * a)
return (
root_a.real if not root_a.imag else root_a,
root_a.real if not root_a.imag else root_a,
)
def SCREAMING_SNAKE_CASE_ ( ):
'''simple docstring'''
lowercase_ , lowercase_ = quadratic_roots(a=5 , b=6 , c=1 )
print(F'The solutions are: {solutiona} and {solutiona}' )
if __name__ == "__main__":
main()
| 601 | 1 |
from maths.is_square_free import is_square_free
from maths.prime_factors import prime_factors
def UpperCamelCase ( __magic_name__ : int ) -> int:
"""simple docstring"""
lowercase__ = prime_factors(__magic_name__ )
if is_square_free(__magic_name__ ):
return -1 if len(__magic_name__ ) % 2 else 1
return 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 15 | """simple docstring"""
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_a : List[Any] = logging.get_logger(__name__)
_a : Dict = {
'microsoft/unispeech-sat-base-100h-libri-ft': (
'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json'
),
# See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}
class __A ( SCREAMING_SNAKE_CASE_ ):
_UpperCamelCase : Dict = "unispeech-sat"
def __init__( self , a__=32 , a__=768 , a__=12 , a__=12 , a__=3072 , a__="gelu" , a__=0.1 , a__=0.1 , a__=0.1 , a__=0.0 , a__=0.0 , a__=0.1 , a__=0.1 , a__=0.0_2 , a__=1e-5 , a__="group" , a__="gelu" , a__=(512, 512, 512, 512, 512, 512, 512) , a__=(5, 2, 2, 2, 2, 2, 2) , a__=(10, 3, 3, 3, 3, 2, 2) , a__=False , a__=128 , a__=16 , a__=False , a__=True , a__=0.0_5 , a__=10 , a__=2 , a__=0.0 , a__=10 , a__=0 , a__=320 , a__=2 , a__=0.1 , a__=100 , a__=256 , a__=256 , a__=0.1 , a__="mean" , a__=False , a__=False , a__=256 , a__=(512, 512, 512, 512, 1500) , a__=(5, 3, 3, 1, 1) , a__=(1, 2, 3, 1, 1) , a__=512 , a__=0 , a__=1 , a__=2 , a__=504 , **a__ , ):
super().__init__(**a__ , pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ )
_lowerCAmelCase : Any = hidden_size
_lowerCAmelCase : int = feat_extract_norm
_lowerCAmelCase : Any = feat_extract_activation
_lowerCAmelCase : List[Any] = list(a__ )
_lowerCAmelCase : List[str] = list(a__ )
_lowerCAmelCase : Dict = list(a__ )
_lowerCAmelCase : str = conv_bias
_lowerCAmelCase : Optional[Any] = num_conv_pos_embeddings
_lowerCAmelCase : Union[str, Any] = num_conv_pos_embedding_groups
_lowerCAmelCase : int = len(self.conv_dim )
_lowerCAmelCase : Optional[Any] = num_hidden_layers
_lowerCAmelCase : int = intermediate_size
_lowerCAmelCase : Tuple = hidden_act
_lowerCAmelCase : Dict = num_attention_heads
_lowerCAmelCase : str = hidden_dropout
_lowerCAmelCase : Any = attention_dropout
_lowerCAmelCase : Optional[Any] = activation_dropout
_lowerCAmelCase : Dict = feat_proj_dropout
_lowerCAmelCase : List[str] = final_dropout
_lowerCAmelCase : Union[str, Any] = layerdrop
_lowerCAmelCase : Union[str, Any] = layer_norm_eps
_lowerCAmelCase : str = initializer_range
_lowerCAmelCase : List[Any] = vocab_size
_lowerCAmelCase : str = num_clusters
_lowerCAmelCase : Optional[Any] = do_stable_layer_norm
_lowerCAmelCase : Optional[Any] = use_weighted_layer_sum
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
""" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
F" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,"
F" `len(config.conv_kernel) = {len(self.conv_kernel )}`." )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
_lowerCAmelCase : Tuple = apply_spec_augment
_lowerCAmelCase : Optional[Any] = mask_time_prob
_lowerCAmelCase : List[Any] = mask_time_length
_lowerCAmelCase : List[Any] = mask_time_min_masks
_lowerCAmelCase : Optional[Any] = mask_feature_prob
_lowerCAmelCase : str = mask_feature_length
_lowerCAmelCase : Any = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
_lowerCAmelCase : int = num_codevectors_per_group
_lowerCAmelCase : Tuple = num_codevector_groups
_lowerCAmelCase : str = contrastive_logits_temperature
_lowerCAmelCase : Optional[int] = feat_quantizer_dropout
_lowerCAmelCase : Any = num_negatives
_lowerCAmelCase : Optional[int] = codevector_dim
_lowerCAmelCase : List[Any] = proj_codevector_dim
_lowerCAmelCase : Optional[int] = diversity_loss_weight
# ctc loss
_lowerCAmelCase : Union[str, Any] = ctc_loss_reduction
_lowerCAmelCase : List[str] = ctc_zero_infinity
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
_lowerCAmelCase : Optional[int] = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
_lowerCAmelCase : int = list(a__ )
_lowerCAmelCase : List[Any] = list(a__ )
_lowerCAmelCase : Union[str, Any] = list(a__ )
_lowerCAmelCase : List[str] = xvector_output_dim
@property
def __A ( self ):
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 213 | 0 |
'''simple docstring'''
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union
import pyarrow as pa
if TYPE_CHECKING:
from .features import FeatureType
@dataclass
class UpperCAmelCase :
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = 42
SCREAMING_SNAKE_CASE_ = None
# Automatically constructed
SCREAMING_SNAKE_CASE_ = "dict"
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = field(default='Translation' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ )
def __call__( self ) -> Optional[Any]:
'''simple docstring'''
return pa.struct({lang: pa.string() for lang in sorted(self.languages )} )
def UpperCamelCase( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]:
'''simple docstring'''
from .features import Value
return {k: Value('string' ) for k in sorted(self.languages )}
@dataclass
class UpperCAmelCase :
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
# Automatically constructed
SCREAMING_SNAKE_CASE_ = "dict"
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = field(default='TranslationVariableLanguages' , init=UpperCAmelCase__ , repr=UpperCAmelCase__ )
def UpperCamelCase( self ) -> Dict:
'''simple docstring'''
lowerCamelCase_ = sorted(set(self.languages ) ) if self.languages else None
lowerCamelCase_ = len(self.languages ) if self.languages else None
def __call__( self ) -> Optional[Any]:
'''simple docstring'''
return pa.struct({'language': pa.list_(pa.string() ), 'translation': pa.list_(pa.string() )} )
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = set(self.languages )
if self.languages and set(SCREAMING_SNAKE_CASE_ ) - lang_set:
raise ValueError(
f'''Some languages in example ({", ".join(sorted(set(SCREAMING_SNAKE_CASE_ ) - lang_set ) )}) are not in valid set ({", ".join(SCREAMING_SNAKE_CASE_ )}).''' )
# Convert dictionary into tuples, splitting out cases where there are
# multiple translations for a single language.
lowerCamelCase_ = []
for lang, text in translation_dict.items():
if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
translation_tuples.append((lang, text) )
else:
translation_tuples.extend([(lang, el) for el in text] )
# Ensure translations are in ascending order by language code.
lowerCamelCase_ ,lowerCamelCase_ = zip(*sorted(SCREAMING_SNAKE_CASE_ ) )
return {"language": languages, "translation": translations}
def UpperCamelCase( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]:
'''simple docstring'''
from .features import Sequence, Value
return {
"language": Sequence(Value('string' ) ),
"translation": Sequence(Value('string' ) ),
}
| 384 |
'''simple docstring'''
import os
from collections import deque
import torch
from torch.utils.data import Dataset
class UpperCAmelCase ( UpperCAmelCase__ ):
'''simple docstring'''
def __init__( self , SCREAMING_SNAKE_CASE_="" , SCREAMING_SNAKE_CASE_="train" ) -> List[Any]:
'''simple docstring'''
assert os.path.isdir(SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = []
lowerCamelCase_ = os.listdir(SCREAMING_SNAKE_CASE_ )
for story_filename in story_filenames_list:
if "summary" in story_filename:
continue
lowerCamelCase_ = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
if not os.path.isfile(SCREAMING_SNAKE_CASE_ ):
continue
self.documents.append(SCREAMING_SNAKE_CASE_ )
def __len__( self ) -> List[str]:
'''simple docstring'''
return len(self.documents )
def __getitem__( self , SCREAMING_SNAKE_CASE_ ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase_ = self.documents[idx]
lowerCamelCase_ = document_path.split('/' )[-1]
with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as source:
lowerCamelCase_ = source.read()
lowerCamelCase_ ,lowerCamelCase_ = process_story(SCREAMING_SNAKE_CASE_ )
return document_name, story_lines, summary_lines
def _UpperCamelCase ( __UpperCamelCase ) -> Union[str, Any]:
lowerCamelCase_ = list(filter(lambda __UpperCamelCase : len(__UpperCamelCase ) != 0 ,[line.strip() for line in raw_story.split('\n' )] ) )
# for some unknown reason some lines miss a period, add it
lowerCamelCase_ = [_add_missing_period(__UpperCamelCase ) for line in nonempty_lines]
# gather article lines
lowerCamelCase_ = []
lowerCamelCase_ = deque(__UpperCamelCase )
while True:
try:
lowerCamelCase_ = lines.popleft()
if element.startswith('@highlight' ):
break
story_lines.append(__UpperCamelCase )
except IndexError:
# if "@highlight" is absent from the file we pop
# all elements until there is None, raising an exception.
return story_lines, []
# gather summary lines
lowerCamelCase_ = list(filter(lambda __UpperCamelCase : not t.startswith('@highlight' ) ,__UpperCamelCase ) )
return story_lines, summary_lines
def _UpperCamelCase ( __UpperCamelCase ) -> Optional[int]:
lowerCamelCase_ = ['.', '!', '?', '...', '\'', '`', '"', '\u2019', '\u2019', ')']
if line.startswith('@highlight' ):
return line
if line[-1] in END_TOKENS:
return line
return line + "."
def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]:
if len(__UpperCamelCase ) > block_size:
return sequence[:block_size]
else:
sequence.extend([pad_token_id] * (block_size - len(__UpperCamelCase )) )
return sequence
def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> List[Any]:
lowerCamelCase_ = torch.ones_like(__UpperCamelCase )
lowerCamelCase_ = sequence == pad_token_id
lowerCamelCase_ = 0
return mask
def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple:
lowerCamelCase_ = [tokenizer.encode(__UpperCamelCase ) for line in story_lines]
lowerCamelCase_ = [token for sentence in story_lines_token_ids for token in sentence]
lowerCamelCase_ = [tokenizer.encode(__UpperCamelCase ) for line in summary_lines]
lowerCamelCase_ = [token for sentence in summary_lines_token_ids for token in sentence]
return story_token_ids, summary_token_ids
def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Optional[int]:
lowerCamelCase_ = []
for sequence in batch:
lowerCamelCase_ = -1
lowerCamelCase_ = []
for s in sequence:
if s == separator_token_id:
sentence_num += 1
embeddings.append(sentence_num % 2 )
batch_embeddings.append(__UpperCamelCase )
return torch.tensor(__UpperCamelCase )
| 384 | 1 |
"""simple docstring"""
from __future__ import annotations
def _lowerCAmelCase ( lowerCamelCase__ : int = 4 ) -> list[list[int]]:
_SCREAMING_SNAKE_CASE : str = abs(__lowerCAmelCase ) or 4
return [[1 + x + y * row_size for x in range(__lowerCAmelCase )] for y in range(__lowerCAmelCase )]
def _lowerCAmelCase ( lowerCamelCase__ : List[str] ) -> list[list[int]]:
return reverse_row(transpose(__lowerCAmelCase ) )
# OR.. transpose(reverse_column(matrix))
def _lowerCAmelCase ( lowerCamelCase__ : Optional[Any] ) -> list[list[int]]:
return reverse_row(reverse_column(__lowerCAmelCase ) )
# OR.. reverse_column(reverse_row(matrix))
def _lowerCAmelCase ( lowerCamelCase__ : Optional[Any] ) -> list[list[int]]:
return reverse_column(transpose(__lowerCAmelCase ) )
# OR.. transpose(reverse_row(matrix))
def _lowerCAmelCase ( lowerCamelCase__ : Optional[Any] ) -> list[list[int]]:
_SCREAMING_SNAKE_CASE : List[str] = [list(__lowerCAmelCase ) for x in zip(*__lowerCAmelCase )]
return matrix
def _lowerCAmelCase ( lowerCamelCase__ : str ) -> list[list[int]]:
_SCREAMING_SNAKE_CASE : Dict = matrix[::-1]
return matrix
def _lowerCAmelCase ( lowerCamelCase__ : List[str] ) -> list[list[int]]:
_SCREAMING_SNAKE_CASE : Optional[Any] = [x[::-1] for x in matrix]
return matrix
def _lowerCAmelCase ( lowerCamelCase__ : Union[str, Any] ) -> None:
for i in matrix:
print(*__lowerCAmelCase )
if __name__ == "__main__":
lowercase_ : List[str] = make_matrix()
print('''\norigin:\n''')
print_matrix(matrix)
print('''\nrotate 90 counterclockwise:\n''')
print_matrix(rotate_aa(matrix))
lowercase_ : Optional[int] = make_matrix()
print('''\norigin:\n''')
print_matrix(matrix)
print('''\nrotate 180:\n''')
print_matrix(rotate_aaa(matrix))
lowercase_ : Optional[int] = make_matrix()
print('''\norigin:\n''')
print_matrix(matrix)
print('''\nrotate 270 counterclockwise:\n''')
print_matrix(rotate_aaa(matrix))
| 572 |
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import MgpstrProcessor, ViTImageProcessor
@require_torch
@require_vision
class __a ( unittest.TestCase ):
_lowerCAmelCase : int = ViTImageProcessor if is_vision_available() else None
@property
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
UpperCamelCase__ : List[str] = (3, 32, 1_28)
UpperCamelCase__ : str = tempfile.mkdtemp()
# fmt: off
UpperCamelCase__ : Optional[int] = ["[GO]", "[s]", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
# fmt: on
UpperCamelCase__ : Tuple = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) )
UpperCamelCase__ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(SCREAMING_SNAKE_CASE ) + "\n" )
UpperCamelCase__ : Any = {
"do_normalize": False,
"do_resize": True,
"image_processor_type": "ViTImageProcessor",
"resample": 3,
"size": {"height": 32, "width": 1_28},
}
UpperCamelCase__ : Tuple = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE )
with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp:
json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def __lowercase ( self : int , **SCREAMING_SNAKE_CASE : Dict ):
'''simple docstring'''
return MgpstrTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE )
def __lowercase ( self : List[str] , **SCREAMING_SNAKE_CASE : Union[str, Any] ):
'''simple docstring'''
return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE )
def __lowercase ( self : Any ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def __lowercase ( self : List[Any] ):
'''simple docstring'''
UpperCamelCase__ : Optional[Any] = np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )
UpperCamelCase__ : str = Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE , 0 , -1 ) )
return image_input
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
UpperCamelCase__ : Optional[Any] = self.get_tokenizer()
UpperCamelCase__ : Tuple = self.get_image_processor()
UpperCamelCase__ : Union[str, Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
processor.save_pretrained(self.tmpdirname )
UpperCamelCase__ : int = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE )
self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.char_tokenizer , SCREAMING_SNAKE_CASE )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE )
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
UpperCamelCase__ : Any = self.get_tokenizer()
UpperCamelCase__ : Union[str, Any] = self.get_image_processor()
UpperCamelCase__ : int = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
processor.save_pretrained(self.tmpdirname )
UpperCamelCase__ : Union[str, Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" )
UpperCamelCase__ : List[Any] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 )
UpperCamelCase__ : Optional[Any] = MgpstrProcessor.from_pretrained(
self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=SCREAMING_SNAKE_CASE , padding_value=1.0 )
self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.char_tokenizer , SCREAMING_SNAKE_CASE )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE )
def __lowercase ( self : Tuple ):
'''simple docstring'''
UpperCamelCase__ : List[Any] = self.get_image_processor()
UpperCamelCase__ : int = self.get_tokenizer()
UpperCamelCase__ : Optional[Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[str] = self.prepare_image_inputs()
UpperCamelCase__ : List[Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="np" )
UpperCamelCase__ : Optional[Any] = processor(images=SCREAMING_SNAKE_CASE , return_tensors="np" )
for key in input_image_proc.keys():
self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 )
def __lowercase ( self : Tuple ):
'''simple docstring'''
UpperCamelCase__ : Union[str, Any] = self.get_image_processor()
UpperCamelCase__ : Dict = self.get_tokenizer()
UpperCamelCase__ : Union[str, Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : int = "test"
UpperCamelCase__ : Optional[Any] = processor(text=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Tuple = tokenizer(SCREAMING_SNAKE_CASE )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
UpperCamelCase__ : Optional[Any] = self.get_image_processor()
UpperCamelCase__ : Optional[Any] = self.get_tokenizer()
UpperCamelCase__ : int = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Dict = "test"
UpperCamelCase__ : int = self.prepare_image_inputs()
UpperCamelCase__ : Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE , images=SCREAMING_SNAKE_CASE )
self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "labels"] )
# test if it raises when no input is passed
with pytest.raises(SCREAMING_SNAKE_CASE ):
processor()
def __lowercase ( self : Any ):
'''simple docstring'''
UpperCamelCase__ : Optional[Any] = self.get_image_processor()
UpperCamelCase__ : int = self.get_tokenizer()
UpperCamelCase__ : Optional[int] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]]
UpperCamelCase__ : Any = processor.char_decode(SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Tuple = [seq.replace(" " , "" ) for seq in decoded_tok]
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def __lowercase ( self : Dict ):
'''simple docstring'''
UpperCamelCase__ : Any = self.get_image_processor()
UpperCamelCase__ : List[str] = self.get_tokenizer()
UpperCamelCase__ : List[Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : List[str] = None
UpperCamelCase__ : List[Any] = self.prepare_image_inputs()
UpperCamelCase__ : Optional[Any] = processor(text=SCREAMING_SNAKE_CASE , images=SCREAMING_SNAKE_CASE )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
def __lowercase ( self : Optional[Any] ):
'''simple docstring'''
UpperCamelCase__ : Dict = self.get_image_processor()
UpperCamelCase__ : Dict = self.get_tokenizer()
UpperCamelCase__ : int = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE )
UpperCamelCase__ : Optional[int] = torch.randn(1 , 27 , 38 )
UpperCamelCase__ : Any = torch.randn(1 , 27 , 5_02_57 )
UpperCamelCase__ : Optional[Any] = torch.randn(1 , 27 , 3_05_22 )
UpperCamelCase__ : List[str] = processor.batch_decode([char_input, bpe_input, wp_input] )
self.assertListEqual(list(results.keys() ) , ["generated_text", "scores", "char_preds", "bpe_preds", "wp_preds"] ) | 228 | 0 |
from typing import Any, Callable, Dict, List, Optional, Union
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionPipeline,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
lowercase : Optional[Any] = "CompVis/stable-diffusion-v1-1"
lowercase : Any = "CompVis/stable-diffusion-v1-2"
lowercase : List[Any] = "CompVis/stable-diffusion-v1-3"
lowercase : Tuple = "CompVis/stable-diffusion-v1-4"
class __lowercase ( _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , ) -> str:
super()._init_()
A : List[str] = StableDiffusionPipeline.from_pretrained(__UpperCAmelCase )
A : Tuple = StableDiffusionPipeline.from_pretrained(__UpperCAmelCase )
A : Any = StableDiffusionPipeline.from_pretrained(__UpperCAmelCase )
A : str = StableDiffusionPipeline(
vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , requires_safety_checker=__UpperCAmelCase , )
self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea )
@property
def snake_case ( self ) -> Dict[str, Any]:
return {k: getattr(self , __UpperCAmelCase ) for k in self.config.keys() if not k.startswith('''_''' )}
def snake_case ( self , __UpperCAmelCase = "auto" ) -> Tuple:
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
A : Optional[int] = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(__UpperCAmelCase )
def snake_case ( self ) -> Tuple:
self.enable_attention_slicing(__UpperCAmelCase )
@torch.no_grad()
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 50 , __UpperCAmelCase = 7.5 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 , **__UpperCAmelCase , ) -> Union[str, Any]:
return self.pipea(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
@torch.no_grad()
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 50 , __UpperCAmelCase = 7.5 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 , **__UpperCAmelCase , ) -> Optional[int]:
return self.pipea(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
@torch.no_grad()
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 50 , __UpperCAmelCase = 7.5 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 , **__UpperCAmelCase , ) -> Optional[Any]:
return self.pipea(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
@torch.no_grad()
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 50 , __UpperCAmelCase = 7.5 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 , **__UpperCAmelCase , ) -> Dict:
return self.pipea(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
@torch.no_grad()
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 5_12 , __UpperCAmelCase = 50 , __UpperCAmelCase = 7.5 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 , **__UpperCAmelCase , ) -> Union[str, Any]:
A : int = '''cuda''' if torch.cuda.is_available() else '''cpu'''
self.to(__UpperCAmelCase )
# Checks if the height and width are divisible by 8 or not
if height % 8 != 0 or width % 8 != 0:
raise ValueError(f'`height` and `width` must be divisible by 8 but are {height} and {width}.' )
# Get first result from Stable Diffusion Checkpoint v1.1
A : List[Any] = self.textaimg_sda_a(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
# Get first result from Stable Diffusion Checkpoint v1.2
A : Union[str, Any] = self.textaimg_sda_a(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
# Get first result from Stable Diffusion Checkpoint v1.3
A : Tuple = self.textaimg_sda_a(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
# Get first result from Stable Diffusion Checkpoint v1.4
A : int = self.textaimg_sda_a(
prompt=__UpperCAmelCase , height=__UpperCAmelCase , width=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , output_type=__UpperCAmelCase , return_dict=__UpperCAmelCase , callback=__UpperCAmelCase , callback_steps=__UpperCAmelCase , **__UpperCAmelCase , )
# Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
| 707 |
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Features, Value
from .base import TaskTemplate
@dataclass(frozen=_SCREAMING_SNAKE_CASE )
class __lowercase ( _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
UpperCAmelCase_ : str = field(default='''summarization''' , metadata={'''include_in_asdict_even_if_is_default''': True} )
UpperCAmelCase_ : ClassVar[Features] = Features({'''text''': Value('''string''' )} )
UpperCAmelCase_ : ClassVar[Features] = Features({'''summary''': Value('''string''' )} )
UpperCAmelCase_ : str = "text"
UpperCAmelCase_ : str = "summary"
@property
def snake_case ( self ) -> Dict[str, str]:
return {self.text_column: "text", self.summary_column: "summary"}
| 423 | 0 |
def _lowercase ( __UpperCamelCase : float ):
if edge <= 0 or not isinstance(__UpperCamelCase , __UpperCamelCase ):
raise ValueError("""Length must be a positive.""" )
return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2)
def _lowercase ( __UpperCamelCase : float ):
if edge <= 0 or not isinstance(__UpperCamelCase , __UpperCamelCase ):
raise ValueError("""Length must be a positive.""" )
return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 214 |
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
lowerCAmelCase : Union[str, Any] = _symbol_database.Default()
lowerCAmelCase : int = _descriptor_pool.Default().AddSerializedFile(
b'''\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'''
)
lowerCAmelCase : List[str] = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, '''sentencepiece_model_pb2''', _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
lowerCAmelCase : Tuple = None
lowerCAmelCase : List[Any] = b'''H\003'''
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
lowerCAmelCase : Tuple = 45
lowerCAmelCase : Optional[int] = 1581
lowerCAmelCase : Dict = 1517
lowerCAmelCase : Any = 1570
lowerCAmelCase : Any = 1584
lowerCAmelCase : Optional[Any] = 1793
lowerCAmelCase : Optional[Any] = 1795
lowerCAmelCase : List[str] = 1916
lowerCAmelCase : Any = 1864
lowerCAmelCase : Dict = 1905
lowerCAmelCase : Dict = 1919
lowerCAmelCase : Any = 2429
lowerCAmelCase : List[Any] = 2208
lowerCAmelCase : Tuple = 2418
lowerCAmelCase : List[Any] = 2323
lowerCAmelCase : List[str] = 2407
# @@protoc_insertion_point(module_scope)
| 214 | 1 |
'''simple docstring'''
from math import factorial
UpperCAmelCase_ : dict[str, int] = {str(digit): factorial(digit) for digit in range(10)}
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> Tuple:
"""simple docstring"""
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise TypeError("""Parameter number must be int""" )
if number < 0:
raise ValueError("""Parameter number must be greater than or equal to 0""" )
# Converts number in string to iterate on its digits and adds its factorial.
return sum(DIGIT_FACTORIAL[digit] for digit in str(__lowerCAmelCase ) )
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 60 , __magic_name__ : int = 100_0000 ) -> List[Any]:
"""simple docstring"""
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise TypeError("""Parameters chain_length and number_limit must be int""" )
if chain_length <= 0 or number_limit <= 0:
raise ValueError(
"""Parameters chain_length and number_limit must be greater than 0""" )
# the counter for the chains with the exact desired length
UpperCamelCase :int = 0
# the cached sizes of the previous chains
UpperCamelCase :Any = {}
for start_chain_element in range(1 , __lowerCAmelCase ):
# The temporary set will contain the elements of the chain
UpperCamelCase :Dict = set()
UpperCamelCase :Optional[int] = 0
# Stop computing the chain when you find a cached size, a repeating item or the
# length is greater then the desired one.
UpperCamelCase :str = start_chain_element
while (
chain_element not in chain_sets_lengths
and chain_element not in chain_set
and chain_set_length <= chain_length
):
chain_set.add(__lowerCAmelCase )
chain_set_length += 1
UpperCamelCase :Dict = digit_factorial_sum(__lowerCAmelCase )
if chain_element in chain_sets_lengths:
chain_set_length += chain_sets_lengths[chain_element]
UpperCamelCase :List[Any] = chain_set_length
# If chain contains the exact amount of elements increase the counter
if chain_set_length == chain_length:
chains_counter += 1
return chains_counter
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F'''{solution()}''')
| 709 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
UpperCAmelCase_ : Optional[int] = {
'''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''],
'''tokenization_xlm''': ['''XLMTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : Union[str, Any] = [
'''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''XLMForMultipleChoice''',
'''XLMForQuestionAnswering''',
'''XLMForQuestionAnsweringSimple''',
'''XLMForSequenceClassification''',
'''XLMForTokenClassification''',
'''XLMModel''',
'''XLMPreTrainedModel''',
'''XLMWithLMHeadModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : List[str] = [
'''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFXLMForMultipleChoice''',
'''TFXLMForQuestionAnsweringSimple''',
'''TFXLMForSequenceClassification''',
'''TFXLMForTokenClassification''',
'''TFXLMMainLayer''',
'''TFXLMModel''',
'''TFXLMPreTrainedModel''',
'''TFXLMWithLMHeadModel''',
]
if TYPE_CHECKING:
from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig
from .tokenization_xlm import XLMTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xlm import (
XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
XLMForMultipleChoice,
XLMForQuestionAnswering,
XLMForQuestionAnsweringSimple,
XLMForSequenceClassification,
XLMForTokenClassification,
XLMModel,
XLMPreTrainedModel,
XLMWithLMHeadModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_xlm import (
TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXLMForMultipleChoice,
TFXLMForQuestionAnsweringSimple,
TFXLMForSequenceClassification,
TFXLMForTokenClassification,
TFXLMMainLayer,
TFXLMModel,
TFXLMPreTrainedModel,
TFXLMWithLMHeadModel,
)
else:
import sys
UpperCAmelCase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 590 | 0 |
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_xlnet import XLNetTokenizer
else:
UpperCamelCase__ = None
UpperCamelCase__ = logging.get_logger(__name__)
UpperCamelCase__ = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
UpperCamelCase__ = {
"vocab_file": {
"xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model",
"xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model",
},
"tokenizer_file": {
"xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json",
"xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json",
},
}
UpperCamelCase__ = {
"xlnet-base-cased": None,
"xlnet-large-cased": None,
}
UpperCamelCase__ = "▁"
# Segments (not really needed)
UpperCamelCase__ = 0
UpperCamelCase__ = 1
UpperCamelCase__ = 2
UpperCamelCase__ = 3
UpperCamelCase__ = 4
class __SCREAMING_SNAKE_CASE ( _a ):
snake_case : str = VOCAB_FILES_NAMES
snake_case : int = PRETRAINED_VOCAB_FILES_MAP
snake_case : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case : List[Any] = """left"""
snake_case : List[Any] = XLNetTokenizer
def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=False , __lowerCAmelCase=True , __lowerCAmelCase=False , __lowerCAmelCase="<s>" , __lowerCAmelCase="</s>" , __lowerCAmelCase="<unk>" , __lowerCAmelCase="<sep>" , __lowerCAmelCase="<pad>" , __lowerCAmelCase="<cls>" , __lowerCAmelCase="<mask>" , __lowerCAmelCase=["<eop>", "<eod>"] , **__lowerCAmelCase , ):
# Mask token behave like a normal word, i.e. include the space before it
UpperCamelCase__ = AddedToken(__lowerCAmelCase , lstrip=__lowerCAmelCase , rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else mask_token
super().__init__(
vocab_file=__lowerCAmelCase , tokenizer_file=__lowerCAmelCase , do_lower_case=__lowerCAmelCase , remove_space=__lowerCAmelCase , keep_accents=__lowerCAmelCase , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , additional_special_tokens=__lowerCAmelCase , **__lowerCAmelCase , )
UpperCamelCase__ = 3
UpperCamelCase__ = do_lower_case
UpperCamelCase__ = remove_space
UpperCamelCase__ = keep_accents
UpperCamelCase__ = vocab_file
UpperCamelCase__ = False if not self.vocab_file else True
def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ):
UpperCamelCase__ = [self.sep_token_id]
UpperCamelCase__ = [self.cls_token_id]
if token_ids_a is None:
return token_ids_a + sep + cls
return token_ids_a + sep + token_ids_a + sep + cls
def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ):
UpperCamelCase__ = [self.sep_token_id]
UpperCamelCase__ = [2]
if token_ids_a is None:
return len(token_ids_a + sep ) * [0] + cls_segment_id
return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id
def _lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ):
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(__lowerCAmelCase ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
UpperCamelCase__ = os.path.join(
__lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ):
copyfile(self.vocab_file , __lowerCAmelCase )
return (out_vocab_file,)
| 619 |
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
# python ./utils/get_modified_files.py utils src tests examples
#
# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
# since the output of this script is fed into Makefile commands it doesn't print a newline after the results
import re
import subprocess
import sys
UpperCamelCase__ = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
UpperCamelCase__ = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode("utf-8").split()
UpperCamelCase__ = "|".join(sys.argv[1:])
UpperCamelCase__ = re.compile(rf"""^({joined_dirs}).*?\.py$""")
UpperCamelCase__ = [x for x in modified_files if regex.match(x)]
print(" ".join(relevant_modified_files), end="")
| 619 | 1 |
import unittest
import numpy as np
import torch
from torch import nn
from transformers import (
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModelWithProjection,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
)
from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class A__ ( __magic_name__ , unittest.TestCase ):
lowercase = KandinskyVaaPriorPipeline
lowercase = ['prompt']
lowercase = ['prompt', 'negative_prompt']
lowercase = [
'num_images_per_prompt',
'generator',
'num_inference_steps',
'latents',
'negative_prompt',
'guidance_scale',
'output_type',
'return_dict',
]
lowercase = False
@property
def _lowerCamelCase ( self : int ):
'''simple docstring'''
return 32
@property
def _lowerCamelCase ( self : List[str] ):
'''simple docstring'''
return 32
@property
def _lowerCamelCase ( self : str ):
'''simple docstring'''
return self.time_input_dim
@property
def _lowerCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
return self.time_input_dim * 4
@property
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
return 100
@property
def _lowerCamelCase ( self : str ):
'''simple docstring'''
lowerCAmelCase__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
return tokenizer
@property
def _lowerCamelCase ( self : Optional[int] ):
'''simple docstring'''
torch.manual_seed(0 )
lowerCAmelCase__ : Optional[Any] = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , )
return CLIPTextModelWithProjection(a )
@property
def _lowerCamelCase ( self : Tuple ):
'''simple docstring'''
torch.manual_seed(0 )
lowerCAmelCase__ : List[str] = {
'num_attention_heads': 2,
'attention_head_dim': 12,
'embedding_dim': self.text_embedder_hidden_size,
'num_layers': 1,
}
lowerCAmelCase__ : Union[str, Any] = PriorTransformer(**a )
# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
lowerCAmelCase__ : Optional[int] = nn.Parameter(torch.ones(model.clip_std.shape ) )
return model
@property
def _lowerCamelCase ( self : Dict ):
'''simple docstring'''
torch.manual_seed(0 )
lowerCAmelCase__ : str = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , )
lowerCAmelCase__ : str = CLIPVisionModelWithProjection(a )
return model
@property
def _lowerCamelCase ( self : str ):
'''simple docstring'''
lowerCAmelCase__ : Dict = CLIPImageProcessor(
crop_size=224 , do_center_crop=a , do_normalize=a , do_resize=a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , )
return image_processor
def _lowerCamelCase ( self : Dict ):
'''simple docstring'''
lowerCAmelCase__ : Tuple = self.dummy_prior
lowerCAmelCase__ : List[str] = self.dummy_image_encoder
lowerCAmelCase__ : List[Any] = self.dummy_text_encoder
lowerCAmelCase__ : Tuple = self.dummy_tokenizer
lowerCAmelCase__ : Optional[Any] = self.dummy_image_processor
lowerCAmelCase__ : Any = UnCLIPScheduler(
variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1_000 , clip_sample=a , clip_sample_range=10.0 , )
lowerCAmelCase__ : int = {
'prior': prior,
'image_encoder': image_encoder,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'scheduler': scheduler,
'image_processor': image_processor,
}
return components
def _lowerCamelCase ( self : List[str] , a : Dict , a : List[str]=0 ):
'''simple docstring'''
if str(a ).startswith('mps' ):
lowerCAmelCase__ : int = torch.manual_seed(a )
else:
lowerCAmelCase__ : str = torch.Generator(device=a ).manual_seed(a )
lowerCAmelCase__ : Dict = {
'prompt': 'horse',
'generator': generator,
'guidance_scale': 4.0,
'num_inference_steps': 2,
'output_type': 'np',
}
return inputs
def _lowerCamelCase ( self : List[str] ):
'''simple docstring'''
lowerCAmelCase__ : Dict = 'cpu'
lowerCAmelCase__ : Union[str, Any] = self.get_dummy_components()
lowerCAmelCase__ : Any = self.pipeline_class(**a )
lowerCAmelCase__ : Union[str, Any] = pipe.to(a )
pipe.set_progress_bar_config(disable=a )
lowerCAmelCase__ : Union[str, Any] = pipe(**self.get_dummy_inputs(a ) )
lowerCAmelCase__ : List[Any] = output.image_embeds
lowerCAmelCase__ : Optional[Any] = pipe(
**self.get_dummy_inputs(a ) , return_dict=a , )[0]
lowerCAmelCase__ : Any = image[0, -10:]
lowerCAmelCase__ : Dict = image_from_tuple[0, -10:]
assert image.shape == (1, 32)
lowerCAmelCase__ : str = np.array(
[-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
@skip_mps
def _lowerCamelCase ( self : int ):
'''simple docstring'''
lowerCAmelCase__ : Dict = torch_device == 'cpu'
lowerCAmelCase__ : Optional[Any] = True
lowerCAmelCase__ : Any = False
self._test_inference_batch_single_identical(
test_max_difference=a , relax_max_difference=a , test_mean_pixel_difference=a , )
@skip_mps
def _lowerCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
lowerCAmelCase__ : Any = torch_device == 'cpu'
lowerCAmelCase__ : int = False
self._test_attention_slicing_forward_pass(
test_max_difference=a , test_mean_pixel_difference=a , ) | 715 |
import inspect
from typing import List, Optional, Tuple, Union
import numpy as np
import PIL
import torch
import torch.utils.checkpoint
from ...models import UNetaDModel, VQModel
from ...schedulers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> List[str]:
lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = image.size
lowerCAmelCase__ , lowerCAmelCase__ : str = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
lowerCAmelCase__ : Any = image.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] )
lowerCAmelCase__ : int = np.array(SCREAMING_SNAKE_CASE_ ).astype(np.floataa ) / 255.0
lowerCAmelCase__ : Optional[int] = image[None].transpose(0 , 3 , 1 , 2 )
lowerCAmelCase__ : List[Any] = torch.from_numpy(SCREAMING_SNAKE_CASE_ )
return 2.0 * image - 1.0
class A__ ( __magic_name__ ):
def __init__( self : List[str] , a : VQModel , a : UNetaDModel , a : Union[
DDIMScheduler,
PNDMScheduler,
LMSDiscreteScheduler,
EulerDiscreteScheduler,
EulerAncestralDiscreteScheduler,
DPMSolverMultistepScheduler,
] , ):
'''simple docstring'''
super().__init__()
self.register_modules(vqvae=a , unet=a , scheduler=a )
@torch.no_grad()
def __call__( self : int , a : Union[torch.Tensor, PIL.Image.Image] = None , a : Optional[int] = 1 , a : Optional[int] = 100 , a : Optional[float] = 0.0 , a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a : Optional[str] = "pil" , a : bool = True , ):
'''simple docstring'''
if isinstance(a , PIL.Image.Image ):
lowerCAmelCase__ : str = 1
elif isinstance(a , torch.Tensor ):
lowerCAmelCase__ : Union[str, Any] = image.shape[0]
else:
raise ValueError(f'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(a )}''' )
if isinstance(a , PIL.Image.Image ):
lowerCAmelCase__ : List[Any] = preprocess(a )
lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = image.shape[-2:]
# in_channels should be 6: 3 for latents, 3 for low resolution image
lowerCAmelCase__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width)
lowerCAmelCase__ : Optional[Any] = next(self.unet.parameters() ).dtype
lowerCAmelCase__ : List[str] = randn_tensor(a , generator=a , device=self.device , dtype=a )
lowerCAmelCase__ : Any = image.to(device=self.device , dtype=a )
# set timesteps and move to the correct device
self.scheduler.set_timesteps(a , device=self.device )
lowerCAmelCase__ : Optional[Any] = self.scheduler.timesteps
# scale the initial noise by the standard deviation required by the scheduler
lowerCAmelCase__ : Optional[Any] = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
lowerCAmelCase__ : Union[str, Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
lowerCAmelCase__ : List[str] = {}
if accepts_eta:
lowerCAmelCase__ : List[Any] = eta
for t in self.progress_bar(a ):
# concat latents and low resolution image in the channel dimension.
lowerCAmelCase__ : Union[str, Any] = torch.cat([latents, image] , dim=1 )
lowerCAmelCase__ : Dict = self.scheduler.scale_model_input(a , a )
# predict the noise residual
lowerCAmelCase__ : Tuple = self.unet(a , a ).sample
# compute the previous noisy sample x_t -> x_t-1
lowerCAmelCase__ : List[str] = self.scheduler.step(a , a , a , **a ).prev_sample
# decode the image latents with the VQVAE
lowerCAmelCase__ : Dict = self.vqvae.decode(a ).sample
lowerCAmelCase__ : Tuple = torch.clamp(a , -1.0 , 1.0 )
lowerCAmelCase__ : Tuple = image / 2 + 0.5
lowerCAmelCase__ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowerCAmelCase__ : int = self.numpy_to_pil(a )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=a ) | 69 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
SCREAMING_SNAKE_CASE_:int = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_:Union[str, Any] = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""}
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
__lowerCamelCase : int = "openai-gpt"
__lowerCamelCase : Dict = {
"max_position_embeddings": "n_positions",
"hidden_size": "n_embd",
"num_attention_heads": "n_head",
"num_hidden_layers": "n_layer",
}
def __init__( self, lowerCamelCase__=4_0478, lowerCamelCase__=512, lowerCamelCase__=768, lowerCamelCase__=12, lowerCamelCase__=12, lowerCamelCase__="gelu", lowerCamelCase__=0.1, lowerCamelCase__=0.1, lowerCamelCase__=0.1, lowerCamelCase__=1e-5, lowerCamelCase__=0.02, lowerCamelCase__="cls_index", lowerCamelCase__=True, lowerCamelCase__=None, lowerCamelCase__=True, lowerCamelCase__=0.1, **lowerCamelCase__, ):
A : Any = vocab_size
A : Dict = n_positions
A : Tuple = n_embd
A : Any = n_layer
A : Dict = n_head
A : Union[str, Any] = afn
A : Dict = resid_pdrop
A : Union[str, Any] = embd_pdrop
A : Any = attn_pdrop
A : Any = layer_norm_epsilon
A : Optional[Any] = initializer_range
A : Union[str, Any] = summary_type
A : Union[str, Any] = summary_use_proj
A : str = summary_activation
A : Optional[Any] = summary_first_dropout
A : Optional[int] = summary_proj_to_labels
super().__init__(**lowerCamelCase__ )
| 662 |
import unittest
from transformers import BertGenerationConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import BertGenerationDecoder, BertGenerationEncoder
class SCREAMING_SNAKE_CASE__ :
'''simple docstring'''
def __init__( self, lowerCamelCase__, lowerCamelCase__=13, lowerCamelCase__=7, lowerCamelCase__=True, lowerCamelCase__=True, lowerCamelCase__=99, lowerCamelCase__=32, lowerCamelCase__=5, lowerCamelCase__=4, lowerCamelCase__=37, lowerCamelCase__="gelu", lowerCamelCase__=0.1, lowerCamelCase__=0.1, lowerCamelCase__=50, lowerCamelCase__=0.02, lowerCamelCase__=True, lowerCamelCase__=None, ):
A : List[str] = parent
A : List[str] = batch_size
A : Optional[int] = seq_length
A : Optional[int] = is_training
A : Tuple = use_input_mask
A : Optional[Any] = vocab_size
A : str = hidden_size
A : Any = num_hidden_layers
A : List[Any] = num_attention_heads
A : Optional[int] = intermediate_size
A : int = hidden_act
A : Dict = hidden_dropout_prob
A : Optional[Any] = attention_probs_dropout_prob
A : List[Any] = max_position_embeddings
A : int = initializer_range
A : Tuple = use_labels
A : List[str] = scope
def _lowerCAmelCase ( self ):
A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size )
A : int = None
if self.use_input_mask:
A : Tuple = random_attention_mask([self.batch_size, self.seq_length] )
if self.use_labels:
A : Tuple = ids_tensor([self.batch_size, self.seq_length], self.vocab_size )
A : List[Any] = self.get_config()
return config, input_ids, input_mask, token_labels
def _lowerCAmelCase ( self ):
return BertGenerationConfig(
vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, is_decoder=lowerCamelCase__, initializer_range=self.initializer_range, )
def _lowerCAmelCase ( self ):
(
(
A
) , (
A
) , (
A
) , (
A
) ,
) : List[Any] = self.prepare_config_and_inputs()
A : Any = True
A : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], vocab_size=2 )
return (
config,
input_ids,
input_mask,
token_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__, ):
A : str = BertGenerationEncoder(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
A : Optional[int] = model(lowerCamelCase__, attention_mask=lowerCamelCase__ )
A : List[str] = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) )
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__, ):
A : List[str] = True
A : Union[str, Any] = BertGenerationEncoder(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
A : Any = model(
lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, )
A : Optional[Any] = model(
lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, )
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) )
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, **lowerCamelCase__, ):
A : Union[str, Any] = True
A : Optional[int] = True
A : Optional[int] = BertGenerationDecoder(config=lowerCamelCase__ ).to(lowerCamelCase__ ).eval()
# first forward pass
A : int = model(
lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, use_cache=lowerCamelCase__, )
A : List[str] = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
A : Optional[Any] = ids_tensor((self.batch_size, 3), config.vocab_size )
A : int = ids_tensor((self.batch_size, 3), vocab_size=2 )
# append to next input_ids and
A : List[str] = torch.cat([input_ids, next_tokens], dim=-1 )
A : Union[str, Any] = torch.cat([input_mask, next_mask], dim=-1 )
A : List[str] = model(
lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, output_hidden_states=lowerCamelCase__, )["""hidden_states"""][0]
A : Any = model(
lowerCamelCase__, attention_mask=lowerCamelCase__, encoder_hidden_states=lowerCamelCase__, encoder_attention_mask=lowerCamelCase__, past_key_values=lowerCamelCase__, output_hidden_states=lowerCamelCase__, )["""hidden_states"""][0]
# select random slice
A : Any = ids_tensor((1,), output_from_past.shape[-1] ).item()
A : Tuple = output_from_no_past[:, -3:, random_slice_idx].detach()
A : Dict = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(lowerCamelCase__, lowerCamelCase__, atol=1e-3 ) )
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, *lowerCamelCase__, ):
A : Optional[int] = BertGenerationDecoder(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
A : List[str] = model(lowerCamelCase__, attention_mask=lowerCamelCase__, labels=lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) )
def _lowerCAmelCase ( self ):
A , A , A , A : str = self.prepare_config_and_inputs()
A : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ):
'''simple docstring'''
__lowerCamelCase : Any = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
__lowerCamelCase : int = (BertGenerationDecoder,) if is_torch_available() else ()
__lowerCamelCase : List[Any] = (
{"feature-extraction": BertGenerationEncoder, "text-generation": BertGenerationDecoder}
if is_torch_available()
else {}
)
def _lowerCAmelCase ( self ):
A : Any = BertGenerationEncoderTester(self )
A : Optional[int] = ConfigTester(self, config_class=lowerCamelCase__, hidden_size=37 )
def _lowerCAmelCase ( self ):
self.config_tester.run_common_tests()
def _lowerCAmelCase ( self ):
A : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase__ )
def _lowerCAmelCase ( self ):
A , A , A , A : Optional[Any] = self.model_tester.prepare_config_and_inputs()
A : Any = """bert"""
self.model_tester.create_and_check_model(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ )
def _lowerCAmelCase ( self ):
A : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*lowerCamelCase__ )
def _lowerCAmelCase ( self ):
A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCamelCase__ )
def _lowerCAmelCase ( self ):
# This regression test was failing with PyTorch < 1.3
(
(
A
) , (
A
) , (
A
) , (
A
) , (
A
) , (
A
) ,
) : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder()
A : int = None
self.model_tester.create_and_check_model_as_decoder(
lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, )
def _lowerCAmelCase ( self ):
A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_for_causal_lm(*lowerCamelCase__ )
@slow
def _lowerCAmelCase ( self ):
A : Tuple = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" )
self.assertIsNotNone(lowerCamelCase__ )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _lowerCAmelCase ( self ):
A : Optional[int] = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" )
A : Optional[int] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] )
with torch.no_grad():
A : Union[str, Any] = model(lowerCamelCase__ )[0]
A : List[Any] = torch.Size([1, 8, 1024] )
self.assertEqual(output.shape, lowerCamelCase__ )
A : Tuple = torch.tensor(
[[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]] )
self.assertTrue(torch.allclose(output[:, :3, :3], lowerCamelCase__, atol=1e-4 ) )
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _lowerCAmelCase ( self ):
A : Optional[Any] = BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" )
A : List[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] )
with torch.no_grad():
A : Dict = model(lowerCamelCase__ )[0]
A : List[str] = torch.Size([1, 8, 5_0358] )
self.assertEqual(output.shape, lowerCamelCase__ )
A : Optional[Any] = torch.tensor(
[[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]] )
self.assertTrue(torch.allclose(output[:, :3, :3], lowerCamelCase__, atol=1e-4 ) )
| 662 | 1 |
def lowerCAmelCase ( _lowerCAmelCase : float , _lowerCAmelCase : float ):
"""simple docstring"""
return price * (1 + tax_rate)
if __name__ == "__main__":
print(F'''{price_plus_tax(1_0_0, 0.2_5) = }''')
print(F'''{price_plus_tax(1_2_5.5_0, 0.0_5) = }''')
| 364 |
import inspect
import unittest
from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, 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 torch import nn
from transformers import RegNetForImageClassification, RegNetModel
from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class _UpperCamelCase :
def __init__( self :List[Any] , lowerCamelCase :Optional[Any] , lowerCamelCase :Any=3 , lowerCamelCase :List[str]=32 , lowerCamelCase :List[str]=3 , lowerCamelCase :List[str]=10 , lowerCamelCase :List[Any]=[10, 20, 30, 40] , lowerCamelCase :Optional[Any]=[1, 1, 2, 1] , lowerCamelCase :List[str]=True , lowerCamelCase :List[Any]=True , lowerCamelCase :str="relu" , lowerCamelCase :Optional[Any]=3 , lowerCamelCase :List[str]=None , ) -> Union[str, Any]:
UpperCAmelCase__ = parent
UpperCAmelCase__ = batch_size
UpperCAmelCase__ = image_size
UpperCAmelCase__ = num_channels
UpperCAmelCase__ = embeddings_size
UpperCAmelCase__ = hidden_sizes
UpperCAmelCase__ = depths
UpperCAmelCase__ = is_training
UpperCAmelCase__ = use_labels
UpperCAmelCase__ = hidden_act
UpperCAmelCase__ = num_labels
UpperCAmelCase__ = scope
UpperCAmelCase__ = len(lowerCamelCase )
def UpperCAmelCase_ ( self :Union[str, Any] ) -> List[str]:
UpperCAmelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCAmelCase__ = None
if self.use_labels:
UpperCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels )
UpperCAmelCase__ = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase_ ( self :Tuple ) -> Optional[int]:
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , )
def UpperCAmelCase_ ( self :str , lowerCamelCase :Dict , lowerCamelCase :Optional[int] , lowerCamelCase :Union[str, Any] ) -> Dict:
UpperCAmelCase__ = RegNetModel(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
UpperCAmelCase__ = model(lowerCamelCase )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def UpperCAmelCase_ ( self :Union[str, Any] , lowerCamelCase :Union[str, Any] , lowerCamelCase :Tuple , lowerCamelCase :List[str] ) -> Union[str, Any]:
UpperCAmelCase__ = self.num_labels
UpperCAmelCase__ = RegNetForImageClassification(lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
UpperCAmelCase__ = model(lowerCamelCase , labels=lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCAmelCase_ ( self :Any ) -> Optional[Any]:
UpperCAmelCase__ = self.prepare_config_and_inputs()
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = config_and_inputs
UpperCAmelCase__ = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class _UpperCamelCase ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ):
UpperCAmelCase_ = (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
UpperCAmelCase_ = (
{"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
if is_torch_available()
else {}
)
UpperCAmelCase_ = False
UpperCAmelCase_ = False
UpperCAmelCase_ = False
UpperCAmelCase_ = False
def UpperCAmelCase_ ( self :int ) -> Dict:
UpperCAmelCase__ = RegNetModelTester(self )
UpperCAmelCase__ = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase )
def UpperCAmelCase_ ( self :str ) -> Tuple:
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def UpperCAmelCase_ ( self :Any ) -> List[str]:
return
@unittest.skip(reason="RegNet does not use inputs_embeds" )
def UpperCAmelCase_ ( self :Optional[Any] ) -> Any:
pass
@unittest.skip(reason="RegNet does not support input and output embeddings" )
def UpperCAmelCase_ ( self :Tuple ) -> Union[str, Any]:
pass
def UpperCAmelCase_ ( self :List[str] ) -> Tuple:
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase__ = model_class(lowerCamelCase )
UpperCAmelCase__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCAmelCase__ = [*signature.parameters.keys()]
UpperCAmelCase__ = ["pixel_values"]
self.assertListEqual(arg_names[:1] , lowerCamelCase )
def UpperCAmelCase_ ( self :Dict ) -> List[Any]:
UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase )
def UpperCAmelCase_ ( self :Optional[Any] ) -> int:
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase__ = model_class(config=lowerCamelCase )
for name, module in model.named_modules():
if isinstance(lowerCamelCase , (nn.BatchNormad, nn.GroupNorm) ):
self.assertTrue(
torch.all(module.weight == 1 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , )
self.assertTrue(
torch.all(module.bias == 0 ) , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , )
def UpperCAmelCase_ ( self :Optional[int] ) -> List[Any]:
def check_hidden_states_output(lowerCamelCase :Optional[int] , lowerCamelCase :int , lowerCamelCase :Optional[int] ):
UpperCAmelCase__ = model_class(lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
with torch.no_grad():
UpperCAmelCase__ = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) )
UpperCAmelCase__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
UpperCAmelCase__ = self.model_tester.num_stages
self.assertEqual(len(lowerCamelCase ) , expected_num_stages + 1 )
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , )
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
UpperCAmelCase__ = ["basic", "bottleneck"]
for model_class in self.all_model_classes:
for layer_type in layers_type:
UpperCAmelCase__ = layer_type
UpperCAmelCase__ = True
check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCAmelCase__ = True
check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase )
def UpperCAmelCase_ ( self :Dict ) -> Union[str, Any]:
UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCamelCase )
@slow
def UpperCAmelCase_ ( self :Tuple ) -> Tuple:
for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase__ = RegNetModel.from_pretrained(lowerCamelCase )
self.assertIsNotNone(lowerCamelCase )
def lowerCAmelCase ( ):
"""simple docstring"""
UpperCAmelCase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class _UpperCamelCase ( unittest.TestCase ):
@cached_property
def UpperCAmelCase_ ( self :Any ) -> Optional[Any]:
return (
AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def UpperCAmelCase_ ( self :Tuple ) -> Union[str, Any]:
UpperCAmelCase__ = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(lowerCamelCase )
UpperCAmelCase__ = self.default_image_processor
UpperCAmelCase__ = prepare_img()
UpperCAmelCase__ = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase )
# forward pass
with torch.no_grad():
UpperCAmelCase__ = model(**lowerCamelCase )
# verify the logits
UpperCAmelCase__ = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , lowerCamelCase )
UpperCAmelCase__ = torch.tensor([-0.41_80, -1.50_51, -3.48_36] ).to(lowerCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1e-4 ) )
| 364 | 1 |
import copy
from typing import Dict, List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
lowercase_ : Dict = {
'''facebook/mask2former-swin-small-coco-instance''': (
'''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json'''
)
# See all Mask2Former models at https://huggingface.co/models?filter=mask2former
}
lowercase_ : Union[str, Any] = logging.get_logger(__name__)
class lowercase ( a_ ):
"""simple docstring"""
_UpperCamelCase : Optional[int] = "mask2former"
_UpperCamelCase : List[str] = ["swin"]
_UpperCamelCase : Tuple = {"hidden_size": "hidden_dim"}
def __init__( self : Tuple , lowerCamelCase_ : Optional[Dict] = None , lowerCamelCase_ : int = 2_56 , lowerCamelCase_ : int = 2_56 , lowerCamelCase_ : int = 2_56 , lowerCamelCase_ : int = 10_24 , lowerCamelCase_ : str = "relu" , lowerCamelCase_ : int = 6 , lowerCamelCase_ : int = 10 , lowerCamelCase_ : int = 8 , lowerCamelCase_ : float = 0.0 , lowerCamelCase_ : int = 20_48 , lowerCamelCase_ : bool = False , lowerCamelCase_ : bool = False , lowerCamelCase_ : int = 4 , lowerCamelCase_ : int = 2_55 , lowerCamelCase_ : int = 1_00 , lowerCamelCase_ : float = 0.1 , lowerCamelCase_ : float = 2.0 , lowerCamelCase_ : float = 5.0 , lowerCamelCase_ : float = 5.0 , lowerCamelCase_ : int = 1_25_44 , lowerCamelCase_ : float = 3.0 , lowerCamelCase_ : float = 0.75 , lowerCamelCase_ : float = 0.02 , lowerCamelCase_ : float = 1.0 , lowerCamelCase_ : bool = True , lowerCamelCase_ : List[int] = [4, 8, 16, 32] , lowerCamelCase_ : bool = None , **lowerCamelCase_ : Dict , ):
'''simple docstring'''
if backbone_config is None:
logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' )
_snake_case : List[str] = CONFIG_MAPPING['swin'](
image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=lowerCamelCase_ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , )
if isinstance(lowerCamelCase_ , lowerCamelCase_ ):
_snake_case : Optional[int] = backbone_config.pop('model_type' )
_snake_case : Tuple = CONFIG_MAPPING[backbone_model_type]
_snake_case : Dict = config_class.from_dict(lowerCamelCase_ )
# 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 Mask2Former. '''
f'''Supported model types: {','.join(self.backbones_supported )}''' )
_snake_case : Tuple = backbone_config
_snake_case : Any = feature_size
_snake_case : int = mask_feature_size
_snake_case : Tuple = hidden_dim
_snake_case : Dict = encoder_feedforward_dim
_snake_case : Any = activation_function
_snake_case : List[str] = encoder_layers
_snake_case : int = decoder_layers
_snake_case : int = num_attention_heads
_snake_case : Optional[int] = dropout
_snake_case : int = dim_feedforward
_snake_case : Tuple = pre_norm
_snake_case : List[str] = enforce_input_projection
_snake_case : str = common_stride
_snake_case : str = ignore_value
_snake_case : str = num_queries
_snake_case : List[str] = no_object_weight
_snake_case : Any = class_weight
_snake_case : int = mask_weight
_snake_case : List[Any] = dice_weight
_snake_case : Dict = train_num_points
_snake_case : int = oversample_ratio
_snake_case : List[Any] = importance_sample_ratio
_snake_case : str = init_std
_snake_case : Dict = init_xavier_std
_snake_case : Union[str, Any] = use_auxiliary_loss
_snake_case : List[Any] = feature_strides
_snake_case : str = output_auxiliary_logits
_snake_case : List[Any] = decoder_layers
super().__init__(**lowerCamelCase_ )
@classmethod
def __UpperCAmelCase ( cls : List[Any] , lowerCamelCase_ : PretrainedConfig , **lowerCamelCase_ : List[Any] ):
'''simple docstring'''
return cls(
backbone_config=lowerCamelCase_ , **lowerCamelCase_ , )
def __UpperCAmelCase ( self : Union[str, Any] ):
'''simple docstring'''
_snake_case : int = copy.deepcopy(self.__dict__ )
_snake_case : int = self.backbone_config.to_dict()
_snake_case : int = self.__class__.model_type
return output
| 304 |
from typing import List, Optional, Tuple
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_herbert import HerbertTokenizer
lowercase_ : Union[str, Any] = logging.get_logger(__name__)
lowercase_ : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}
lowercase_ : Union[str, Any] = {
'''vocab_file''': {
'''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json'''
},
'''merges_file''': {
'''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt'''
},
}
lowercase_ : List[str] = {'''allegro/herbert-base-cased''': 514}
lowercase_ : Union[str, Any] = {}
class lowercase ( a_ ):
"""simple docstring"""
_UpperCamelCase : Tuple = VOCAB_FILES_NAMES
_UpperCamelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
_UpperCamelCase : Any = PRETRAINED_INIT_CONFIGURATION
_UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_UpperCamelCase : Union[str, Any] = HerbertTokenizer
def __init__( self : int , lowerCamelCase_ : int=None , lowerCamelCase_ : Any=None , lowerCamelCase_ : Dict=None , lowerCamelCase_ : Dict="<s>" , lowerCamelCase_ : str="<unk>" , lowerCamelCase_ : Dict="<pad>" , lowerCamelCase_ : Dict="<mask>" , lowerCamelCase_ : Optional[Any]="</s>" , **lowerCamelCase_ : List[Any] , ):
'''simple docstring'''
super().__init__(
lowerCamelCase_ , lowerCamelCase_ , tokenizer_file=lowerCamelCase_ , cls_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , **lowerCamelCase_ , )
def __UpperCAmelCase ( self : Any , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ):
'''simple docstring'''
_snake_case : List[Any] = [self.cls_token_id]
_snake_case : str = [self.sep_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def __UpperCAmelCase ( self : List[str] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None , lowerCamelCase_ : bool = False ):
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCamelCase_ )) + [1]
return [1] + ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1]
def __UpperCAmelCase ( self : Optional[Any] , lowerCamelCase_ : List[int] , lowerCamelCase_ : Optional[List[int]] = None ):
'''simple docstring'''
_snake_case : List[str] = [self.sep_token_id]
_snake_case : Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __UpperCAmelCase ( self : Any , lowerCamelCase_ : str , lowerCamelCase_ : Optional[str] = None ):
'''simple docstring'''
_snake_case : Union[str, Any] = self._tokenizer.model.save(lowerCamelCase_ , name=lowerCamelCase_ )
return tuple(lowerCamelCase_ )
| 304 | 1 |
"""simple docstring"""
from random import randint
from tempfile import TemporaryFile
import numpy as np
def _SCREAMING_SNAKE_CASE ( __snake_case : Optional[int] , __snake_case : Optional[int] , __snake_case : Dict ):
'''simple docstring'''
lowercase = 0
if start < end:
lowercase = randint(__snake_case , __snake_case )
lowercase = a[end]
lowercase = a[pivot]
lowercase = temp
lowercase , lowercase = _in_place_partition(__snake_case , __snake_case , __snake_case )
count += _in_place_quick_sort(__snake_case , __snake_case , p - 1 )
count += _in_place_quick_sort(__snake_case , p + 1 , __snake_case )
return count
def _SCREAMING_SNAKE_CASE ( __snake_case : List[str] , __snake_case : Tuple , __snake_case : Optional[Any] ):
'''simple docstring'''
lowercase = 0
lowercase = randint(__snake_case , __snake_case )
lowercase = a[end]
lowercase = a[pivot]
lowercase = temp
lowercase = start - 1
for index in range(__snake_case , __snake_case ):
count += 1
if a[index] < a[end]: # check if current val is less than pivot value
lowercase = new_pivot_index + 1
lowercase = a[new_pivot_index]
lowercase = a[index]
lowercase = temp
lowercase = a[new_pivot_index + 1]
lowercase = a[end]
lowercase = temp
return new_pivot_index + 1, count
_UpperCamelCase : List[str] = TemporaryFile()
_UpperCamelCase : Optional[int] = 1_0_0 # 1000 elements are to be sorted
_UpperCamelCase, _UpperCamelCase : Union[str, Any] = 0, 1 # mean and standard deviation
_UpperCamelCase : List[str] = np.random.normal(mu, sigma, p)
np.save(outfile, X)
print('The array is')
print(X)
outfile.seek(0) # using the same array
_UpperCamelCase : Tuple = np.load(outfile)
_UpperCamelCase : int = len(M) - 1
_UpperCamelCase : List[Any] = _in_place_quick_sort(M, 0, r)
print(
'No of Comparisons for 100 elements selected from a standard normal distribution'
'is :'
)
print(z)
| 134 |
"""simple docstring"""
import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union
# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
CONFIG_MAPPING_NAMES,
AutoConfig,
model_type_to_module_name,
replace_list_option_in_docstrings,
)
_UpperCamelCase : str = logging.get_logger(__name__)
_UpperCamelCase : Dict = OrderedDict(
[
('audio-spectrogram-transformer', 'ASTFeatureExtractor'),
('beit', 'BeitFeatureExtractor'),
('chinese_clip', 'ChineseCLIPFeatureExtractor'),
('clap', 'ClapFeatureExtractor'),
('clip', 'CLIPFeatureExtractor'),
('clipseg', 'ViTFeatureExtractor'),
('conditional_detr', 'ConditionalDetrFeatureExtractor'),
('convnext', 'ConvNextFeatureExtractor'),
('cvt', 'ConvNextFeatureExtractor'),
('data2vec-audio', 'Wav2Vec2FeatureExtractor'),
('data2vec-vision', 'BeitFeatureExtractor'),
('deformable_detr', 'DeformableDetrFeatureExtractor'),
('deit', 'DeiTFeatureExtractor'),
('detr', 'DetrFeatureExtractor'),
('dinat', 'ViTFeatureExtractor'),
('donut-swin', 'DonutFeatureExtractor'),
('dpt', 'DPTFeatureExtractor'),
('encodec', 'EncodecFeatureExtractor'),
('flava', 'FlavaFeatureExtractor'),
('glpn', 'GLPNFeatureExtractor'),
('groupvit', 'CLIPFeatureExtractor'),
('hubert', 'Wav2Vec2FeatureExtractor'),
('imagegpt', 'ImageGPTFeatureExtractor'),
('layoutlmv2', 'LayoutLMv2FeatureExtractor'),
('layoutlmv3', 'LayoutLMv3FeatureExtractor'),
('levit', 'LevitFeatureExtractor'),
('maskformer', 'MaskFormerFeatureExtractor'),
('mctct', 'MCTCTFeatureExtractor'),
('mobilenet_v1', 'MobileNetV1FeatureExtractor'),
('mobilenet_v2', 'MobileNetV2FeatureExtractor'),
('mobilevit', 'MobileViTFeatureExtractor'),
('nat', 'ViTFeatureExtractor'),
('owlvit', 'OwlViTFeatureExtractor'),
('perceiver', 'PerceiverFeatureExtractor'),
('poolformer', 'PoolFormerFeatureExtractor'),
('regnet', 'ConvNextFeatureExtractor'),
('resnet', 'ConvNextFeatureExtractor'),
('segformer', 'SegformerFeatureExtractor'),
('sew', 'Wav2Vec2FeatureExtractor'),
('sew-d', 'Wav2Vec2FeatureExtractor'),
('speech_to_text', 'Speech2TextFeatureExtractor'),
('speecht5', 'SpeechT5FeatureExtractor'),
('swiftformer', 'ViTFeatureExtractor'),
('swin', 'ViTFeatureExtractor'),
('swinv2', 'ViTFeatureExtractor'),
('table-transformer', 'DetrFeatureExtractor'),
('timesformer', 'VideoMAEFeatureExtractor'),
('tvlt', 'TvltFeatureExtractor'),
('unispeech', 'Wav2Vec2FeatureExtractor'),
('unispeech-sat', 'Wav2Vec2FeatureExtractor'),
('van', 'ConvNextFeatureExtractor'),
('videomae', 'VideoMAEFeatureExtractor'),
('vilt', 'ViltFeatureExtractor'),
('vit', 'ViTFeatureExtractor'),
('vit_mae', 'ViTFeatureExtractor'),
('vit_msn', 'ViTFeatureExtractor'),
('wav2vec2', 'Wav2Vec2FeatureExtractor'),
('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'),
('wavlm', 'Wav2Vec2FeatureExtractor'),
('whisper', 'WhisperFeatureExtractor'),
('xclip', 'CLIPFeatureExtractor'),
('yolos', 'YolosFeatureExtractor'),
]
)
_UpperCamelCase : str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
def _SCREAMING_SNAKE_CASE ( __snake_case : str ):
'''simple docstring'''
for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
if class_name in extractors:
lowercase = model_type_to_module_name(__snake_case )
lowercase = importlib.import_module(f'.{module_name}' , 'transformers.models' )
try:
return getattr(__snake_case , __snake_case )
except AttributeError:
continue
for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
if getattr(__snake_case , '__name__' , __snake_case ) == class_name:
return extractor
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
# init and we return the proper dummy to get an appropriate error message.
lowercase = importlib.import_module('transformers' )
if hasattr(__snake_case , __snake_case ):
return getattr(__snake_case , __snake_case )
return None
def _SCREAMING_SNAKE_CASE ( __snake_case : Union[str, os.PathLike] , __snake_case : Optional[Union[str, os.PathLike]] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[Dict[str, str]] = None , __snake_case : Optional[Union[bool, str]] = None , __snake_case : Optional[str] = None , __snake_case : bool = False , **__snake_case : int , ):
'''simple docstring'''
lowercase = get_file_from_repo(
__snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , )
if resolved_config_file is None:
logger.info(
'Could not locate the feature extractor configuration file, will try to use the model config instead.' )
return {}
with open(__snake_case , encoding='utf-8' ) as reader:
return json.load(__snake_case )
class a :
def __init__( self ):
raise EnvironmentError(
'AutoFeatureExtractor is designed to be instantiated '
'using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.' )
@classmethod
@replace_list_option_in_docstrings(_lowerCamelCase )
def UpperCamelCase_ ( cls , _lowerCamelCase , **_lowerCamelCase ):
lowercase = kwargs.pop('config' , _lowerCamelCase )
lowercase = kwargs.pop('trust_remote_code' , _lowerCamelCase )
lowercase = True
lowercase , lowercase = FeatureExtractionMixin.get_feature_extractor_dict(_lowerCamelCase , **_lowerCamelCase )
lowercase = config_dict.get('feature_extractor_type' , _lowerCamelCase )
lowercase = None
if "AutoFeatureExtractor" in config_dict.get('auto_map' , {} ):
lowercase = config_dict['auto_map']['AutoFeatureExtractor']
# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
if feature_extractor_class is None and feature_extractor_auto_map is None:
if not isinstance(_lowerCamelCase , _lowerCamelCase ):
lowercase = AutoConfig.from_pretrained(_lowerCamelCase , **_lowerCamelCase )
# It could be in `config.feature_extractor_type``
lowercase = getattr(_lowerCamelCase , 'feature_extractor_type' , _lowerCamelCase )
if hasattr(_lowerCamelCase , 'auto_map' ) and "AutoFeatureExtractor" in config.auto_map:
lowercase = config.auto_map['AutoFeatureExtractor']
if feature_extractor_class is not None:
lowercase = feature_extractor_class_from_name(_lowerCamelCase )
lowercase = feature_extractor_auto_map is not None
lowercase = feature_extractor_class is not None or type(_lowerCamelCase ) in FEATURE_EXTRACTOR_MAPPING
lowercase = resolve_trust_remote_code(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
if has_remote_code and trust_remote_code:
lowercase = get_class_from_dynamic_module(
_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase )
lowercase = kwargs.pop('code_revision' , _lowerCamelCase )
if os.path.isdir(_lowerCamelCase ):
feature_extractor_class.register_for_auto_class()
return feature_extractor_class.from_dict(_lowerCamelCase , **_lowerCamelCase )
elif feature_extractor_class is not None:
return feature_extractor_class.from_dict(_lowerCamelCase , **_lowerCamelCase )
# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
elif type(_lowerCamelCase ) in FEATURE_EXTRACTOR_MAPPING:
lowercase = FEATURE_EXTRACTOR_MAPPING[type(_lowerCamelCase )]
return feature_extractor_class.from_dict(_lowerCamelCase , **_lowerCamelCase )
raise ValueError(
F'Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a '
F'`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following '
F'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}' )
@staticmethod
def UpperCamelCase_ ( _lowerCamelCase , _lowerCamelCase ):
FEATURE_EXTRACTOR_MAPPING.register(_lowerCamelCase , _lowerCamelCase )
| 134 | 1 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import MobileBertConfig, is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TF_MODEL_FOR_PRETRAINING_MAPPING,
TFMobileBertForMaskedLM,
TFMobileBertForMultipleChoice,
TFMobileBertForNextSentencePrediction,
TFMobileBertForPreTraining,
TFMobileBertForQuestionAnswering,
TFMobileBertForSequenceClassification,
TFMobileBertForTokenClassification,
TFMobileBertModel,
)
@require_tf
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
TFMobileBertModel,
TFMobileBertForMaskedLM,
TFMobileBertForNextSentencePrediction,
TFMobileBertForPreTraining,
TFMobileBertForQuestionAnswering,
TFMobileBertForSequenceClassification,
TFMobileBertForTokenClassification,
TFMobileBertForMultipleChoice,
)
if is_tf_available()
else ()
)
lowercase__ = (
{
'feature-extraction': TFMobileBertModel,
'fill-mask': TFMobileBertForMaskedLM,
'question-answering': TFMobileBertForQuestionAnswering,
'text-classification': TFMobileBertForSequenceClassification,
'token-classification': TFMobileBertForTokenClassification,
'zero-shot': TFMobileBertForSequenceClassification,
}
if is_tf_available()
else {}
)
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a=False) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class in get_values(__a):
_UpperCamelCase = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa)
return inputs_dict
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=32 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_input_mask
_UpperCamelCase = use_token_type_ids
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = num_labels
_UpperCamelCase = num_choices
_UpperCamelCase = scope
_UpperCamelCase = embedding_size
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = None
if self.use_input_mask:
_UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length])
_UpperCamelCase = None
if self.use_token_type_ids:
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
_UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices)
_UpperCamelCase = MobileBertConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , embedding_size=self.embedding_size , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = TFMobileBertModel(config=__a)
_UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_UpperCamelCase = model(__a)
_UpperCamelCase = [input_ids, input_mask]
_UpperCamelCase = model(__a)
_UpperCamelCase = model(__a)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = TFMobileBertForMaskedLM(config=__a)
_UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = TFMobileBertForNextSentencePrediction(config=__a)
_UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase = TFMobileBertForPreTraining(config=__a)
_UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_UpperCamelCase = model(__a)
self.parent.assertEqual(
result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = TFMobileBertForSequenceClassification(config=__a)
_UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.num_choices
_UpperCamelCase = TFMobileBertForMultipleChoice(config=__a)
_UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1))
_UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1))
_UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1))
_UpperCamelCase = {
'''input_ids''': multiple_choice_inputs_ids,
'''attention_mask''': multiple_choice_input_mask,
'''token_type_ids''': multiple_choice_token_type_ids,
}
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = TFMobileBertForTokenClassification(config=__a)
_UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = TFMobileBertForQuestionAnswering(config=__a)
_UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = TFMobileBertModelTest.TFMobileBertModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_model(*__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_masked_lm(*__a)
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__a)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__a)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_pretraining(*__a)
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_question_answering(*__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__a)
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_token_classification(*__a)
@slow
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
# for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["google/mobilebert-uncased"]:
_UpperCamelCase = TFMobileBertModel.from_pretrained(__a)
self.assertIsNotNone(__a)
@require_tf
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''')
_UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]])
_UpperCamelCase = model(__a)[0]
_UpperCamelCase = [1, 6, 3_05_22]
self.assertEqual(output.shape , __a)
_UpperCamelCase = tf.constant(
[
[
[-4.591_9547, -9.24_8295, -9.64_5256],
[-6.730_6175, -6.44_0284, -6.605_2837],
[-7.274_3506, -6.784_7915, -6.02_4673],
]
])
tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-4)
| 19 |
"""simple docstring"""
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['image_processor', 'tokenizer']
lowercase__ = 'ViTImageProcessor'
lowercase__ = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self , __a=None , __a=None , **__a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , __a , )
_UpperCamelCase = kwargs.pop('''feature_extractor''')
_UpperCamelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''')
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''')
super().__init__(__a , __a)
def __call__( self , __a=None , __a=None , __a=None , __a=None , **__a) -> Tuple:
'''simple docstring'''
if text is None and visual_prompt is None and images is None:
raise ValueError('''You have to specify either text, visual prompt or images.''')
if text is not None and visual_prompt is not None:
raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''')
if text is not None:
_UpperCamelCase = self.tokenizer(__a , return_tensors=__a , **__a)
if visual_prompt is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if images is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if visual_prompt is not None and images is not None:
_UpperCamelCase = {
'''pixel_values''': image_features.pixel_values,
'''conditional_pixel_values''': prompt_features.pixel_values,
}
return encoding
elif text is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None:
return encoding
elif visual_prompt is not None:
_UpperCamelCase = {
'''conditional_pixel_values''': prompt_features.pixel_values,
}
return encoding
else:
return BatchEncoding(data=dict(**__a) , tensor_type=__a)
def UpperCAmelCase ( self , *__a , **__a) -> Any:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> List[str]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@property
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __a , )
return self.image_processor_class
@property
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __a , )
return self.image_processor
| 19 | 1 |
"""simple docstring"""
import argparse
import json
import os
import tensorstore as ts
import torch
from flax import serialization
from flax.traverse_util import flatten_dict, unflatten_dict
from tensorflow.io import gfile
from transformers.modeling_utils import dtype_byte_size
from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import (
rename_keys,
)
from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
from transformers.utils.hub import convert_file_size_to_int
def lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : int ) -> Dict:
if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3:
# expert layer
__a = flax_key_tuple[:-1] + ('''weight''',)
__a = torch.permute(lowerCAmelCase__ , (0, 2, 1) )
elif flax_key_tuple[-1] == "kernel" and ".".join(lowerCAmelCase__ ):
# linear layer
__a = flax_key_tuple[:-1] + ('''weight''',)
__a = flax_tensor.T
elif flax_key_tuple[-1] in ["scale", "embedding"]:
__a = flax_key_tuple[:-1] + ('''weight''',)
return flax_key_tuple, flax_tensor
def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict ) -> str:
if "metadata" in layer:
__a = layer.split('''metadata''' )
__a = ''''''.join(split_layer[0] )[:-1]
__a = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )]
elif "kvstore" in layer:
__a = layer.split('''kvstore''' )
__a = ''''''.join(split_layer[0] )[:-1]
__a = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )]
else:
__a = layer.split('''/''' )
__a = '''/'''.join(split_layer[:-1] )
__a = (split_layer[-1],)
if "kvstore/path" in layer:
__a = f'''{switch_checkpoint_path}/{checkpoint_info[layer]}'''
elif "kvstore/driver" in layer:
__a = '''file'''
else:
__a = checkpoint_info[layer]
return curr_real_layer_name, split_layer, content
def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any:
__a = rename_keys(lowerCAmelCase__ )
__a = {}
for k, v in current_block.items():
__a = v
__a = new_current_block
torch.save(lowerCAmelCase__ , lowerCAmelCase__ )
def lowercase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str = WEIGHTS_NAME ) -> Optional[Any]:
__a = convert_file_size_to_int(lowerCAmelCase__ )
__a = []
__a = {}
__a = 0
__a = 0
os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ )
with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp:
__a = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target''']
__a = flatten_dict(lowerCAmelCase__ , sep='''/''' )
__a = {}
for layer in checkpoint_info.keys():
__a , __a , __a = get_key_and_tensorstore_dict(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
if curr_real_layer_name in all_layers:
__a = content
else:
__a = {split_layer[-1]: content}
for key in all_layers.keys():
# open tensorstore file
__a = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result()
__a = torch.tensor(lowerCAmelCase__ )
__a = raw_weights.numel() * dtype_byte_size(raw_weights.dtype )
# use the renaming pattern from the small conversion scripts
__a , __a = rename_base_flax_keys(tuple(key.split('''/''' ) ) , lowerCAmelCase__ )
__a = '''/'''.join(lowerCAmelCase__ )
# If this weight is going to tip up over the maximal size, we split.
if current_block_size + weight_size > max_shard_size:
__a = os.path.join(
lowerCAmelCase__ , weights_name.replace('''.bin''' , f'''-{len(lowerCAmelCase__ )+1:05d}-of-???.bin''' ) )
rename_and_save_block(lowerCAmelCase__ , lowerCAmelCase__ )
sharded_state_dicts.append(current_block.keys() )
del current_block
__a = {}
__a = 0
__a = raw_weights.to(getattr(lowerCAmelCase__ , lowerCAmelCase__ ) )
current_block_size += weight_size
total_size += weight_size
# Add the last block
__a = os.path.join(lowerCAmelCase__ , weights_name.replace('''.bin''' , f'''-{len(lowerCAmelCase__ )+1:05d}-of-???.bin''' ) )
rename_and_save_block(lowerCAmelCase__ , lowerCAmelCase__ )
sharded_state_dicts.append(current_block.keys() )
# If we only have one shard, we return it
if len(lowerCAmelCase__ ) == 1:
return {weights_name: sharded_state_dicts[0]}, None
# Otherwise, let's build the index
__a = {}
__a = {}
for idx, shard in enumerate(lowerCAmelCase__ ):
__a = weights_name.replace(
'''.bin''' , f'''-{idx+1:05d}-of-{len(lowerCAmelCase__ ):05d}.bin''' ) # len(sharded_state_dicts):05d}
__a = os.path.join(lowerCAmelCase__ , weights_name.replace('''.bin''' , f'''-{idx+1:05d}-of-???.bin''' ) )
os.rename(lowerCAmelCase__ , os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) )
__a = shard
for key in shard:
__a = shard_file
# Add the metadata
__a = {'''total_size''': total_size}
__a = {'''metadata''': metadata, '''weight_map''': weight_map}
with open(os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) , '''w''' , encoding='''utf-8''' ) as f:
__a = json.dumps(lowerCAmelCase__ , indent=2 , sort_keys=lowerCAmelCase__ ) + '''\n'''
f.write(lowerCAmelCase__ )
return metadata, index
if __name__ == "__main__":
lowercase_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--switch_t5x_checkpoint_path",
default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600",
type=str,
required=False,
help="Path to a directory containing a folder per layer. Follows the original Google format.",
)
parser.add_argument("--max_shard_size", default="10GB", required=False, help="Max shard size")
parser.add_argument("--dtype", default="bfloat16", type=str, required=False, help="dtype of the saved model")
parser.add_argument(
"--pytorch_dump_folder_path",
default="/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted",
type=str,
required=False,
help="Path to the output pytorch model.",
)
lowercase_ = parser.parse_args()
shard_on_the_fly(
args.switch_tax_checkpoint_path,
args.pytorch_dump_folder_path,
args.max_shard_size,
args.dtype,
)
def lowercase ( ) -> int:
from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer
__a = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' )
config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' )
__a = SwitchTransformersForConditionalGeneration.from_pretrained(
'''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' )
__a = TaTokenizer.from_pretrained('''t5-small''' )
__a = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.'''
__a = tokenizer(lowerCAmelCase__ , return_tensors='''pt''' ).input_ids
__a = model.generate(lowerCAmelCase__ , decoder_start_token_id=0 )
print(tokenizer.decode(out[0] ) )
| 700 |
"""simple docstring"""
import pytest
from datasets import inspect_metric, list_metrics, load_metric
@pytest.fixture
def lowercase ( lowerCAmelCase__ : Optional[int] ) -> int:
monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() )
@pytest.fixture
def lowercase ( lowerCAmelCase__ : Any ) -> Any:
class __lowerCAmelCase :
'''simple docstring'''
def __init__( self , _a ):
__a = metric_id
class __lowerCAmelCase :
'''simple docstring'''
__UpperCAmelCase : Any = [MetricMock(__SCREAMING_SNAKE_CASE ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']]
def __UpperCAmelCase ( self ):
return self._metrics
monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() )
@pytest.mark.parametrize(
'''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] )
def lowercase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple ) -> Optional[int]:
if "tmp_path" in args:
__a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args )
with pytest.warns(lowerCAmelCase__ , match='''https://huggingface.co/docs/evaluate''' ):
func(*lowerCAmelCase__ )
| 65 | 0 |
"""simple docstring"""
import doctest
import sys
import warnings
from os.path import abspath, dirname, join
import _pytest
from transformers.testing_utils import HfDoctestModule, HfDocTestParser
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__A : List[str] = abspath(join(dirname(__file__), '''src'''))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)
def A_ ( snake_case_ : Optional[int] ):
'''simple docstring'''
config.addinivalue_line(
"""markers""" ,"""is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested""" )
config.addinivalue_line(
"""markers""" ,"""is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested""" )
config.addinivalue_line("""markers""" ,"""is_pipeline_test: mark test to run only when pipelines are tested""" )
config.addinivalue_line("""markers""" ,"""is_staging_test: mark test to run only in the staging environment""" )
config.addinivalue_line("""markers""" ,"""accelerate_tests: mark test that require accelerate""" )
config.addinivalue_line("""markers""" ,"""tool_tests: mark the tool tests that are run on their specific schedule""" )
def A_ ( snake_case_ : Optional[Any] ):
'''simple docstring'''
from transformers.testing_utils import pytest_addoption_shared
pytest_addoption_shared(snake_case_ )
def A_ ( snake_case_ : Optional[Any] ):
'''simple docstring'''
from transformers.testing_utils import pytest_terminal_summary_main
UpperCamelCase : int = terminalreporter.config.getoption("""--make-reports""" )
if make_reports:
pytest_terminal_summary_main(snake_case_ ,id=snake_case_ )
def A_ ( snake_case_ : List[Any] ,snake_case_ : Optional[int] ):
'''simple docstring'''
# If no tests are collected, pytest exists with code 5, which makes the CI fail.
if exitstatus == 5:
UpperCamelCase : List[Any] = 0
# Doctest custom flag to ignore output.
__A : List[str] = doctest.register_optionflag('''IGNORE_RESULT''')
__A : Optional[Any] = doctest.OutputChecker
class lowerCamelCase ( _lowerCamelCase ):
def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ):
if IGNORE_RESULT & optionflags:
return True
return OutputChecker.check_output(self , _A , _A , _A )
__A : str = CustomOutputChecker
__A : Union[str, Any] = HfDoctestModule
__A : Optional[Any] = HfDocTestParser
| 499 |
"""simple docstring"""
from __future__ import annotations
UpperCAmelCase_ : Tuple = '''Muhammad Umer Farooq'''
UpperCAmelCase_ : List[str] = '''MIT'''
UpperCAmelCase_ : Any = '''1.0.0'''
UpperCAmelCase_ : int = '''Muhammad Umer Farooq'''
UpperCAmelCase_ : Optional[int] = '''contact@muhammadumerfarooq.me'''
UpperCAmelCase_ : Tuple = '''Alpha'''
import re
from html.parser import HTMLParser
from urllib import parse
import requests
class __UpperCAmelCase ( _lowerCamelCase ):
'''simple docstring'''
def __init__( self , _A ):
'''simple docstring'''
super().__init__()
_SCREAMING_SNAKE_CASE =[]
_SCREAMING_SNAKE_CASE =domain
def UpperCamelCase_ ( self , _A , _A ):
'''simple docstring'''
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in urls.
if value not in self.urls:
_SCREAMING_SNAKE_CASE =parse.urljoin(self.domain , _A )
self.urls.append(_A )
def _lowerCAmelCase(a : str ) -> str:
return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] )
def _lowerCAmelCase(a : str ) -> str:
return parse.urlparse(a ).netloc
def _lowerCAmelCase(a : str = "https://github.com" ) -> list[str]:
_SCREAMING_SNAKE_CASE =get_domain_name(a )
# Initialize the parser
_SCREAMING_SNAKE_CASE =Parser(a )
try:
# Open URL
_SCREAMING_SNAKE_CASE =requests.get(a )
# pass the raw HTML to the parser to get links
parser.feed(r.text )
# Get links and loop through
_SCREAMING_SNAKE_CASE =set()
for link in parser.urls:
# open URL.
# read = requests.get(link)
try:
_SCREAMING_SNAKE_CASE =requests.get(a )
# Get the valid email.
_SCREAMING_SNAKE_CASE =re.findall('''[a-zA-Z0-9]+@''' + domain , read.text )
# If not in list then append it.
for email in emails:
valid_emails.add(a )
except ValueError:
pass
except ValueError:
raise SystemExit(1 )
# Finally return a sorted list of email addresses with no duplicates.
return sorted(a )
if __name__ == "__main__":
UpperCAmelCase_ : List[str] = emails_from_url('''https://github.com''')
print(f"{len(emails)} emails found:")
print('''\n'''.join(sorted(emails)))
| 255 | 0 |
"""simple docstring"""
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class __UpperCAmelCase ( _snake_case ):
"""simple docstring"""
_snake_case : Tuple = ['image_processor', 'tokenizer']
_snake_case : Union[str, Any] = 'CLIPImageProcessor'
_snake_case : List[str] = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self : int , A_ : Optional[Any]=None , A_ : List[str]=None , **A_ : Optional[Any] )-> str:
__UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , lowerCAmelCase__ , )
__UpperCamelCase = kwargs.pop("feature_extractor" )
__UpperCamelCase = 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__(lowerCAmelCase__ , lowerCAmelCase__ )
def __call__( self : List[str] , A_ : List[str]=None , A_ : int=None , A_ : Dict=None , **A_ : Tuple )-> Tuple:
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:
__UpperCamelCase = self.tokenizer(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ )
if images is not None:
__UpperCamelCase = self.image_processor(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ )
if text is not None and images is not None:
__UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**lowerCAmelCase__ ) , tensor_type=lowerCAmelCase__ )
def A ( self : Optional[Any] , *A_ : Optional[int] , **A_ : str )-> Dict:
return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
def A ( self : Dict , *A_ : str , **A_ : List[str] )-> int:
return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
@property
def A ( self : Optional[int] )-> str:
__UpperCamelCase = self.tokenizer.model_input_names
__UpperCamelCase = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
@property
def A ( self : List[Any] )-> int:
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , lowerCAmelCase__ , )
return self.image_processor_class
@property
def A ( self : Tuple )-> Optional[int]:
warnings.warn(
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , lowerCAmelCase__ , )
return self.image_processor | 701 |
"""simple docstring"""
import argparse
import json
import os
from tensorflow.core.protobuf.saved_model_pba import SavedModel
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_copies.py
_A = "."
# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model)
_A = [
"Assert",
"AssignVariableOp",
"EmptyTensorList",
"MergeV2Checkpoints",
"ReadVariableOp",
"ResourceGather",
"RestoreV2",
"SaveV2",
"ShardedFilename",
"StatefulPartitionedCall",
"StaticRegexFullMatch",
"VarHandleOp",
]
def lowercase (_snake_case ,_snake_case ,_snake_case ) -> Any:
'''simple docstring'''
__UpperCamelCase = SavedModel()
__UpperCamelCase = []
with open(os.path.join(_snake_case ,"utils" ,"tf_ops" ,"onnx.json" ) ) as f:
__UpperCamelCase = json.load(_snake_case )["opsets"]
for i in range(1 ,opset + 1 ):
onnx_ops.extend(onnx_opsets[str(_snake_case )] )
with open(_snake_case ,"rb" ) as f:
saved_model.ParseFromString(f.read() )
__UpperCamelCase = set()
# Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs)
for meta_graph in saved_model.meta_graphs:
# Add operations in the graph definition
model_op_names.update(node.op for node in meta_graph.graph_def.node )
# Go through the functions in the graph definition
for func in meta_graph.graph_def.library.function:
# Add operations in each function
model_op_names.update(node.op for node in func.node_def )
# Convert to list, sorted if you want
__UpperCamelCase = sorted(_snake_case )
__UpperCamelCase = []
for op in model_op_names:
if op not in onnx_ops and op not in INTERNAL_OPS:
incompatible_ops.append(_snake_case )
if strict and len(_snake_case ) > 0:
raise Exception(f"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops )
elif len(_snake_case ) > 0:
print(f"""Found the following incompatible ops for the opset {opset}:""" )
print(*_snake_case ,sep="\n" )
else:
print(f"""The saved model {saved_model_path} can properly be converted with ONNX.""" )
if __name__ == "__main__":
_A = argparse.ArgumentParser()
parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).")
parser.add_argument(
"--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested."
)
parser.add_argument(
"--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model."
)
parser.add_argument(
"--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)"
)
_A = parser.parse_args()
if args.framework == "onnx":
onnx_compliancy(args.saved_model_path, args.strict, args.opset) | 228 | 0 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
UpperCAmelCase_ = logging.get_logger(__name__)
UpperCAmelCase_ = {
"bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/config.json",
"bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/config.json",
"bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/config.json",
"bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/config.json",
"bert-base-multilingual-uncased": "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json",
"bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json",
"bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/config.json",
"bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/config.json",
"bert-large-uncased-whole-word-masking": (
"https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json"
),
"bert-large-cased-whole-word-masking": (
"https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json"
),
"bert-large-uncased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json"
),
"bert-large-cased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json"
),
"bert-base-cased-finetuned-mrpc": "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json",
"bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json",
"bert-base-german-dbmdz-uncased": "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json",
"cl-tohoku/bert-base-japanese": "https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json",
"cl-tohoku/bert-base-japanese-whole-word-masking": (
"https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json"
),
"cl-tohoku/bert-base-japanese-char": (
"https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json"
),
"cl-tohoku/bert-base-japanese-char-whole-word-masking": (
"https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json"
),
"TurkuNLP/bert-base-finnish-cased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json"
),
"TurkuNLP/bert-base-finnish-uncased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json"
),
"wietsedv/bert-base-dutch-cased": "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json",
# See all BERT models at https://huggingface.co/models?filter=bert
}
class __UpperCamelCase ( A__ ):
__A : Union[str, Any] = """bert"""
def __init__( self , _UpperCamelCase=30522 , _UpperCamelCase=768 , _UpperCamelCase=12 , _UpperCamelCase=12 , _UpperCamelCase=3072 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=512 , _UpperCamelCase=2 , _UpperCamelCase=0.02 , _UpperCamelCase=1e-12 , _UpperCamelCase=0 , _UpperCamelCase="absolute" , _UpperCamelCase=True , _UpperCamelCase=None , **_UpperCamelCase , ):
super().__init__(pad_token_id=_UpperCamelCase , **_UpperCamelCase )
_UpperCAmelCase = vocab_size
_UpperCAmelCase = hidden_size
_UpperCAmelCase = num_hidden_layers
_UpperCAmelCase = num_attention_heads
_UpperCAmelCase = hidden_act
_UpperCAmelCase = intermediate_size
_UpperCAmelCase = hidden_dropout_prob
_UpperCAmelCase = attention_probs_dropout_prob
_UpperCAmelCase = max_position_embeddings
_UpperCAmelCase = type_vocab_size
_UpperCAmelCase = initializer_range
_UpperCAmelCase = layer_norm_eps
_UpperCAmelCase = position_embedding_type
_UpperCAmelCase = use_cache
_UpperCAmelCase = classifier_dropout
class __UpperCamelCase ( A__ ):
@property
def UpperCamelCase( self ):
if self.task == "multiple-choice":
_UpperCAmelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
else:
_UpperCAmelCase = {0: '''batch''', 1: '''sequence'''}
return OrderedDict(
[
('''input_ids''', dynamic_axis),
('''attention_mask''', dynamic_axis),
('''token_type_ids''', dynamic_axis),
] ) | 32 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ..utils import _LazyModule
lowerCamelCase__ = {
"config": [
"EXTERNAL_DATA_FORMAT_SIZE_LIMIT",
"OnnxConfig",
"OnnxConfigWithPast",
"OnnxSeq2SeqConfigWithPast",
"PatchingSpec",
],
"convert": ["export", "validate_model_outputs"],
"features": ["FeaturesManager"],
"utils": ["ParameterFormat", "compute_serialized_parameters_size"],
}
if TYPE_CHECKING:
from .config import (
EXTERNAL_DATA_FORMAT_SIZE_LIMIT,
OnnxConfig,
OnnxConfigWithPast,
OnnxSeqaSeqConfigWithPast,
PatchingSpec,
)
from .convert import export, validate_model_outputs
from .features import FeaturesManager
from .utils import ParameterFormat, compute_serialized_parameters_size
else:
import sys
lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 574 | 0 |
import copy
import inspect
import unittest
from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
require_torch,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import SwiftFormerForImageClassification, SwiftFormerModel
from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowerCAmelCase__:
'''simple docstring'''
def __init__( self : Optional[Any] , __snake_case : Optional[int] , __snake_case : List[str]=13 , __snake_case : Tuple=3 , __snake_case : List[str]=True , __snake_case : List[str]=True , __snake_case : Tuple=0.1 , __snake_case : Dict=0.1 , __snake_case : List[str]=224 , __snake_case : Union[str, Any]=1_000 , __snake_case : List[Any]=[3, 3, 6, 4] , __snake_case : Union[str, Any]=[48, 56, 112, 220] , ):
'''simple docstring'''
UpperCAmelCase_ : Union[str, Any] = parent
UpperCAmelCase_ : str = batch_size
UpperCAmelCase_ : Union[str, Any] = num_channels
UpperCAmelCase_ : Tuple = is_training
UpperCAmelCase_ : Optional[int] = use_labels
UpperCAmelCase_ : Any = hidden_dropout_prob
UpperCAmelCase_ : Optional[int] = attention_probs_dropout_prob
UpperCAmelCase_ : int = num_labels
UpperCAmelCase_ : List[str] = image_size
UpperCAmelCase_ : List[Any] = layer_depths
UpperCAmelCase_ : Union[str, Any] = embed_dims
def _lowerCamelCase ( self : Dict ):
'''simple docstring'''
UpperCAmelCase_ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCAmelCase_ : List[str] = None
if self.use_labels:
UpperCAmelCase_ : Dict = ids_tensor([self.batch_size] , self.num_labels )
UpperCAmelCase_ : List[Any] = self.get_config()
return config, pixel_values, labels
def _lowerCamelCase ( self : Tuple ):
'''simple docstring'''
return SwiftFormerConfig(
depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='''gelu''' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=__snake_case , layer_scale_init_value=1E-5 , )
def _lowerCamelCase ( self : Optional[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : List[str] ):
'''simple docstring'''
UpperCAmelCase_ : int = SwiftFormerModel(config=__snake_case )
model.to(__snake_case )
model.eval()
UpperCAmelCase_ : List[Any] = model(__snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) )
def _lowerCamelCase ( self : Any , __snake_case : Optional[Any] , __snake_case : Any , __snake_case : List[Any] ):
'''simple docstring'''
UpperCAmelCase_ : str = self.num_labels
UpperCAmelCase_ : List[str] = SwiftFormerForImageClassification(__snake_case )
model.to(__snake_case )
model.eval()
UpperCAmelCase_ : List[Any] = model(__snake_case , labels=__snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
UpperCAmelCase_ : Any = SwiftFormerForImageClassification(__snake_case )
model.to(__snake_case )
model.eval()
UpperCAmelCase_ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCAmelCase_ : List[str] = model(__snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowerCamelCase ( self : int ):
'''simple docstring'''
((UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_)) : Union[str, Any] = self.prepare_config_and_inputs()
UpperCAmelCase_ : Optional[Any] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class lowerCAmelCase__( snake_case__ , snake_case__ , unittest.TestCase ):
'''simple docstring'''
A_ : List[str] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
A_ : Union[str, Any] = (
{'feature-extraction': SwiftFormerModel, 'image-classification': SwiftFormerForImageClassification}
if is_torch_available()
else {}
)
A_ : List[str] = False
A_ : Optional[Any] = False
A_ : List[Any] = False
A_ : str = False
A_ : int = False
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase_ : List[str] = SwiftFormerModelTester(self )
UpperCAmelCase_ : List[Any] = ConfigTester(
self , config_class=__snake_case , has_text_modality=__snake_case , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , )
def _lowerCamelCase ( self : int ):
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='''SwiftFormer does not use inputs_embeds''' )
def _lowerCamelCase ( self : Tuple ):
'''simple docstring'''
pass
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase_ : Tuple = model_class(__snake_case )
UpperCAmelCase_ : Optional[int] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__snake_case , nn.Linear ) )
def _lowerCamelCase ( self : Any ):
'''simple docstring'''
UpperCAmelCase_ , UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase_ : List[str] = model_class(__snake_case )
UpperCAmelCase_ : Optional[int] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCAmelCase_ : Union[str, Any] = [*signature.parameters.keys()]
UpperCAmelCase_ : Union[str, Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , __snake_case )
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__snake_case )
def _lowerCamelCase ( self : List[str] ):
'''simple docstring'''
UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__snake_case )
@slow
def _lowerCamelCase ( self : List[str] ):
'''simple docstring'''
for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase_ : int = SwiftFormerModel.from_pretrained(__snake_case )
self.assertIsNotNone(__snake_case )
@unittest.skip(reason='''SwiftFormer does not output attentions''' )
def _lowerCamelCase ( self : Any ):
'''simple docstring'''
pass
def _lowerCamelCase ( self : str ):
'''simple docstring'''
def check_hidden_states_output(__snake_case : Optional[Any] , __snake_case : Optional[int] , __snake_case : Optional[int] ):
UpperCAmelCase_ : int = model_class(__snake_case )
model.to(__snake_case )
model.eval()
with torch.no_grad():
UpperCAmelCase_ : List[Any] = model(**self._prepare_for_class(__snake_case , __snake_case ) )
UpperCAmelCase_ : Union[str, Any] = outputs.hidden_states
UpperCAmelCase_ : List[Any] = 8
self.assertEqual(len(__snake_case ) , __snake_case ) # TODO
# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
# with the width and height being successively divided by 2, after every 2 blocks
for i in range(len(__snake_case ) ):
self.assertEqual(
hidden_states[i].shape , torch.Size(
[
self.model_tester.batch_size,
self.model_tester.embed_dims[i // 2],
(self.model_tester.image_size // 4) // 2 ** (i // 2),
(self.model_tester.image_size // 4) // 2 ** (i // 2),
] ) , )
UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase_ : Tuple = True
check_hidden_states_output(__snake_case , __snake_case , __snake_case )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
UpperCAmelCase_ : List[str] = True
check_hidden_states_output(__snake_case , __snake_case , __snake_case )
def _lowerCamelCase ( self : Any ):
'''simple docstring'''
def _config_zero_init(__snake_case : Optional[Any] ):
UpperCAmelCase_ : str = copy.deepcopy(__snake_case )
for key in configs_no_init.__dict__.keys():
if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
setattr(__snake_case , __snake_case , 1E-10 )
if isinstance(getattr(__snake_case , __snake_case , __snake_case ) , __snake_case ):
UpperCAmelCase_ : List[Any] = _config_zero_init(getattr(__snake_case , __snake_case ) )
setattr(__snake_case , __snake_case , __snake_case )
return configs_no_init
UpperCAmelCase_ , UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common()
UpperCAmelCase_ : List[str] = _config_zero_init(__snake_case )
for model_class in self.all_model_classes:
UpperCAmelCase_ : List[Any] = model_class(config=__snake_case )
for name, param in model.named_parameters():
if param.requires_grad:
self.assertIn(
((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def _lowerCamelCase ( self : int ):
'''simple docstring'''
pass
def snake_case_ ( ):
UpperCAmelCase_ : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
class lowerCAmelCase__( unittest.TestCase ):
'''simple docstring'''
@cached_property
def _lowerCamelCase ( self : int ):
'''simple docstring'''
return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs''' ) if is_vision_available() else None
@slow
def _lowerCamelCase ( self : Dict ):
'''simple docstring'''
UpperCAmelCase_ : Optional[int] = SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs''' ).to(__snake_case )
UpperCAmelCase_ : List[str] = self.default_image_processor
UpperCAmelCase_ : Tuple = prepare_img()
UpperCAmelCase_ : Any = image_processor(images=__snake_case , return_tensors='''pt''' ).to(__snake_case )
# forward pass
with torch.no_grad():
UpperCAmelCase_ : str = model(**__snake_case )
# verify the logits
UpperCAmelCase_ : Dict = torch.Size((1, 1_000) )
self.assertEqual(outputs.logits.shape , __snake_case )
UpperCAmelCase_ : Tuple = torch.tensor([[-2.1703E00, 2.1107E00, -2.0811E00]] ).to(__snake_case )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __snake_case , atol=1E-4 ) ) | 641 |
import fire
from utils import calculate_rouge, save_json
def snake_case_ ( __lowercase , __lowercase , __lowercase=None , **__lowercase ):
UpperCAmelCase_ : Tuple = [x.strip() for x in open(__lowercase ).readlines()]
UpperCAmelCase_ : Dict = [x.strip() for x in open(__lowercase ).readlines()][: len(__lowercase )]
UpperCAmelCase_ : int = calculate_rouge(__lowercase , __lowercase , **__lowercase )
if save_path is not None:
save_json(__lowercase , __lowercase , indent=__lowercase )
return metrics # these print nicely
if __name__ == "__main__":
fire.Fire(calculate_rouge_path) | 641 | 1 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor
from ..utils import is_datasets_available
from .base import PipelineTool
if is_datasets_available():
from datasets import load_dataset
class lowerCAmelCase ( UpperCamelCase_ ):
A_ : str = """microsoft/speecht5_tts"""
A_ : Dict = (
"""This is a tool that reads an English text out loud. It takes an input named `text` which should contain the """
"""text to read (in English) and returns a waveform object containing the sound."""
)
A_ : Any = """text_reader"""
A_ : Dict = SpeechTaProcessor
A_ : str = SpeechTaForTextToSpeech
A_ : Optional[Any] = SpeechTaHifiGan
A_ : Union[str, Any] = ["""text"""]
A_ : Tuple = ["""audio"""]
def _A ( self : int ):
'''simple docstring'''
if self.post_processor is None:
lowerCAmelCase__ : str = "microsoft/speecht5_hifigan"
super().setup()
def _A ( self : int , a__ : Any , a__ : Dict=None ):
'''simple docstring'''
lowerCAmelCase__ : List[str] = self.pre_processor(text=a__ , return_tensors="pt" , truncation=a__ )
if speaker_embeddings is None:
if not is_datasets_available():
raise ImportError("Datasets needs to be installed if not passing speaker embeddings." )
lowerCAmelCase__ : int = load_dataset("Matthijs/cmu-arctic-xvectors" , split="validation" )
lowerCAmelCase__ : Dict = torch.tensor(embeddings_dataset[7305]["xvector"] ).unsqueeze(0 )
return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings}
def _A ( self : Tuple , a__ : int ):
'''simple docstring'''
with torch.no_grad():
return self.model.generate_speech(**a__ )
def _A ( self : Optional[int] , a__ : List[Any] ):
'''simple docstring'''
with torch.no_grad():
return self.post_processor(a__ ).cpu().detach()
| 378 |
'''simple docstring'''
from ....configuration_utils import PretrainedConfig
from ....utils import logging
snake_case = logging.get_logger(__name__)
snake_case = {
"""Visual-Attention-Network/van-base""": (
"""https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json"""
),
}
class lowerCAmelCase ( UpperCamelCase_ ):
A_ : Tuple = """van"""
def __init__( self : List[Any] , a__ : Dict=224 , a__ : Dict=3 , a__ : Union[str, Any]=[7, 3, 3, 3] , a__ : Optional[Any]=[4, 2, 2, 2] , a__ : Optional[Any]=[64, 128, 320, 512] , a__ : List[str]=[3, 3, 12, 3] , a__ : Any=[8, 8, 4, 4] , a__ : Optional[int]="gelu" , a__ : List[Any]=0.02 , a__ : Tuple=1e-6 , a__ : List[str]=1e-2 , a__ : List[str]=0.0 , a__ : List[Any]=0.0 , **a__ : Tuple , ):
'''simple docstring'''
super().__init__(**a__ )
lowerCAmelCase__ : Any = image_size
lowerCAmelCase__ : Tuple = num_channels
lowerCAmelCase__ : List[Any] = patch_sizes
lowerCAmelCase__ : Dict = strides
lowerCAmelCase__ : List[str] = hidden_sizes
lowerCAmelCase__ : Union[str, Any] = depths
lowerCAmelCase__ : Tuple = mlp_ratios
lowerCAmelCase__ : Optional[Any] = hidden_act
lowerCAmelCase__ : Dict = initializer_range
lowerCAmelCase__ : int = layer_norm_eps
lowerCAmelCase__ : Optional[Any] = layer_scale_init_value
lowerCAmelCase__ : List[str] = drop_path_rate
lowerCAmelCase__ : Any = dropout_rate
| 378 | 1 |
import json
import os
from typing import Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
lowerCAmelCase__ = logging.get_logger(__name__)
lowerCAmelCase__ = {"""vocab_file""": """vocab.json"""}
lowerCAmelCase__ = {
"""vocab_file""": {
"""mgp-str""": """https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json""",
}
}
lowerCAmelCase__ = {"""mgp-str""": 2_7}
class lowercase ( _lowercase ):
"""simple docstring"""
a__ = VOCAB_FILES_NAMES
a__ = PRETRAINED_VOCAB_FILES_MAP
a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self , __snake_case , __snake_case="[GO]" , __snake_case="[GO]" , __snake_case="[s]" , __snake_case="[GO]" , **__snake_case):
super().__init__(
unk_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , pad_token=__snake_case , **__snake_case , )
with open(__snake_case , encoding='utf-8') as vocab_handle:
_UpperCamelCase : Tuple = json.load(__snake_case)
_UpperCamelCase : Optional[Any] = {v: k for k, v in self.vocab.items()}
@property
def A__ ( self):
return len(self.vocab)
def A__ ( self):
return dict(self.vocab , **self.added_tokens_encoder)
def A__ ( self , __snake_case):
_UpperCamelCase : List[str] = []
for s in text:
char_tokens.extend(__snake_case)
return char_tokens
def A__ ( self , __snake_case):
return self.vocab.get(__snake_case , self.vocab.get(self.unk_token))
def A__ ( self , __snake_case):
return self.decoder.get(__snake_case)
def A__ ( self , __snake_case , __snake_case = None):
if not os.path.isdir(__snake_case):
logger.error('Vocabulary path ({}) should be a directory'.format(__snake_case))
return
_UpperCamelCase : str = os.path.join(
__snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])
with open(__snake_case , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.vocab , indent=2 , sort_keys=__snake_case , ensure_ascii=__snake_case) + '\n')
return (vocab_file,)
| 648 |
from __future__ import annotations
import matplotlib.pyplot as plt # type: ignore
import numpy
# initial triangle of Koch snowflake
lowerCAmelCase__ = numpy.array([0, 0])
lowerCAmelCase__ = numpy.array([0.5, 0.8_66_02_54])
lowerCAmelCase__ = numpy.array([1, 0])
lowerCAmelCase__ = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
def lowerCamelCase_ ( UpperCAmelCase_ : list[numpy.ndarray] , UpperCAmelCase_ : int ) -> list[numpy.ndarray]:
'''simple docstring'''
_UpperCamelCase : Tuple = initial_vectors
for _ in range(UpperCAmelCase_ ):
_UpperCamelCase : str = iteration_step(UpperCAmelCase_ )
return vectors
def lowerCamelCase_ ( UpperCAmelCase_ : list[numpy.ndarray] ) -> list[numpy.ndarray]:
'''simple docstring'''
_UpperCamelCase : int = []
for i, start_vector in enumerate(vectors[:-1] ):
_UpperCamelCase : Union[str, Any] = vectors[i + 1]
new_vectors.append(UpperCAmelCase_ )
_UpperCamelCase : Tuple = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3 )
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 6_0 ) )
new_vectors.append(start_vector + difference_vector * 2 / 3 )
new_vectors.append(vectors[-1] )
return new_vectors
def lowerCamelCase_ ( UpperCAmelCase_ : numpy.ndarray , UpperCAmelCase_ : float ) -> numpy.ndarray:
'''simple docstring'''
_UpperCamelCase : str = numpy.radians(UpperCAmelCase_ )
_UpperCamelCase , _UpperCamelCase : Optional[Any] = numpy.cos(UpperCAmelCase_ ), numpy.sin(UpperCAmelCase_ )
_UpperCamelCase : Any = numpy.array(((c, -s), (s, c)) )
return numpy.dot(UpperCAmelCase_ , UpperCAmelCase_ )
def lowerCamelCase_ ( UpperCAmelCase_ : list[numpy.ndarray] ) -> None:
'''simple docstring'''
_UpperCamelCase : str = plt.gca()
axes.set_aspect('equal' )
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
_UpperCamelCase , _UpperCamelCase : Dict = zip(*UpperCAmelCase_ )
plt.plot(UpperCAmelCase_ , UpperCAmelCase_ )
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
lowerCAmelCase__ = iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| 648 | 1 |
"""simple docstring"""
_lowercase = '''Tobias Carryer'''
from time import time
class lowerCAmelCase_ :
'''simple docstring'''
def __init__( self : List[Any] ,A_ : str ,A_ : Optional[Any] ,A_ : List[str] ,A_ : List[Any]=int(time() ) ) -> Union[str, Any]: # noqa: B008
A = multiplier
A = increment
A = modulo
A = seed
def _SCREAMING_SNAKE_CASE ( self : Any ) -> int:
A = (self.multiplier * self.seed + self.increment) % self.modulo
return self.seed
if __name__ == "__main__":
# Show the LCG in action.
_lowercase = LinearCongruentialGenerator(1_66_45_25, 10_13_90_42_23, 2 << 31)
while True:
print(lcg.next_number()) | 91 |
"""simple docstring"""
import math
from typing import Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
get_image_size,
is_torch_available,
is_torch_tensor,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_torch_available():
import torch
if is_vision_available():
import PIL
SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__)
def __UpperCAmelCase ( snake_case_ : np.ndarray , snake_case_ : Union[int, Iterable[int]] , snake_case_ : bool , snake_case_ : int ) -> Tuple[int, int]:
"""simple docstring"""
def constraint_to_multiple_of(snake_case_ : Dict , snake_case_ : str , snake_case_ : Dict=0 , snake_case_ : Optional[int]=None ):
_lowerCAmelCase = round(val / multiple ) * multiple
if max_val is not None and x > max_val:
_lowerCAmelCase = math.floor(val / multiple ) * multiple
if x < min_val:
_lowerCAmelCase = math.ceil(val / multiple ) * multiple
return x
_lowerCAmelCase = (output_size, output_size) if isinstance(snake_case_ , snake_case_ ) else output_size
_lowerCAmelCase , _lowerCAmelCase = get_image_size(snake_case_ )
_lowerCAmelCase , _lowerCAmelCase = output_size
# determine new height and width
_lowerCAmelCase = output_height / input_height
_lowerCAmelCase = output_width / input_width
if keep_aspect_ratio:
# scale as little as possible
if abs(1 - scale_width ) < abs(1 - scale_height ):
# fit width
_lowerCAmelCase = scale_width
else:
# fit height
_lowerCAmelCase = scale_height
_lowerCAmelCase = constraint_to_multiple_of(scale_height * input_height , multiple=snake_case_ )
_lowerCAmelCase = constraint_to_multiple_of(scale_width * input_width , multiple=snake_case_ )
return (new_height, new_width)
class __lowerCamelCase ( __lowercase ):
__UpperCamelCase = ['pixel_values']
def __init__(self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BILINEAR , lowerCamelCase = False , lowerCamelCase = 1 , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = None , **lowerCamelCase , ):
'''simple docstring'''
super().__init__(**lowerCamelCase )
_lowerCAmelCase = size if size is not None else {"""height""": 384, """width""": 384}
_lowerCAmelCase = get_size_dict(lowerCamelCase )
_lowerCAmelCase = do_resize
_lowerCAmelCase = size
_lowerCAmelCase = keep_aspect_ratio
_lowerCAmelCase = ensure_multiple_of
_lowerCAmelCase = resample
_lowerCAmelCase = do_rescale
_lowerCAmelCase = rescale_factor
_lowerCAmelCase = do_normalize
_lowerCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_lowerCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase = False , lowerCamelCase = 1 , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ):
'''simple docstring'''
_lowerCAmelCase = get_size_dict(lowerCamelCase )
if "height" not in size or "width" not in size:
raise ValueError(f"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" )
_lowerCAmelCase = get_resize_output_image_size(
lowerCamelCase , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=lowerCamelCase , multiple=lowerCamelCase , )
return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase )
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ):
'''simple docstring'''
return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase )
def A__ (self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ):
'''simple docstring'''
return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase )
def A__ (self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ):
'''simple docstring'''
_lowerCAmelCase = do_resize if do_resize is not None else self.do_resize
_lowerCAmelCase = size if size is not None else self.size
_lowerCAmelCase = get_size_dict(lowerCamelCase )
_lowerCAmelCase = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
_lowerCAmelCase = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
_lowerCAmelCase = resample if resample is not None else self.resample
_lowerCAmelCase = do_rescale if do_rescale is not None else self.do_rescale
_lowerCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_lowerCAmelCase = do_normalize if do_normalize is not None else self.do_normalize
_lowerCAmelCase = image_mean if image_mean is not None else self.image_mean
_lowerCAmelCase = image_std if image_std is not None else self.image_std
_lowerCAmelCase = make_list_of_images(lowerCamelCase )
if not valid_images(lowerCamelCase ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None or resample is None:
raise ValueError("""Size and resample must be specified if do_resize is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# All transformations expect numpy arrays.
_lowerCAmelCase = [to_numpy_array(lowerCamelCase ) for image in images]
if do_resize:
_lowerCAmelCase = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images]
if do_rescale:
_lowerCAmelCase = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images]
if do_normalize:
_lowerCAmelCase = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images]
_lowerCAmelCase = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images]
_lowerCAmelCase = {"""pixel_values""": images}
return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
def A__ (self , lowerCamelCase , lowerCamelCase = None ):
'''simple docstring'''
_lowerCAmelCase = outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(lowerCamelCase ) != len(lowerCamelCase ):
raise ValueError(
"""Make sure that you pass in as many target sizes as the batch dimension of the logits""" )
if is_torch_tensor(lowerCamelCase ):
_lowerCAmelCase = target_sizes.numpy()
_lowerCAmelCase = []
for idx in range(len(lowerCamelCase ) ):
_lowerCAmelCase = torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=lowerCamelCase )
_lowerCAmelCase = resized_logits[0].argmax(dim=0 )
semantic_segmentation.append(lowerCamelCase )
else:
_lowerCAmelCase = logits.argmax(dim=1 )
_lowerCAmelCase = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )]
return semantic_segmentation | 156 | 0 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from diffusers import (
DDIMScheduler,
KandinskyVaaControlnetImgaImgPipeline,
KandinskyVaaPriorEmbaEmbPipeline,
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 _lowercase ( lowercase__ , unittest.TestCase):
"""simple docstring"""
A__ = KandinskyVaaControlnetImgaImgPipeline
A__ = ["image_embeds", "negative_image_embeds", "image", "hint"]
A__ = ["image_embeds", "negative_image_embeds", "image", "hint"]
A__ = [
"generator",
"height",
"width",
"strength",
"guidance_scale",
"num_inference_steps",
"return_dict",
"guidance_scale",
"num_images_per_prompt",
"output_type",
"return_dict",
]
A__ = False
@property
def lowerCAmelCase ( self : str ):
'''simple docstring'''
return 32
@property
def lowerCAmelCase ( self : int ):
'''simple docstring'''
return 32
@property
def lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
return self.time_input_dim
@property
def lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
return self.time_input_dim * 4
@property
def lowerCAmelCase ( self : Any ):
'''simple docstring'''
return 100
@property
def lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
torch.manual_seed(0 )
lowerCamelCase__ : Any = {
"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,
}
lowerCamelCase__ : str = UNetaDConditionModel(**__lowerCamelCase )
return model
@property
def lowerCAmelCase ( self : Union[str, Any] ):
'''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 lowerCAmelCase ( self : Optional[Any] ):
'''simple docstring'''
torch.manual_seed(0 )
lowerCamelCase__ : Any = VQModel(**self.dummy_movq_kwargs )
return model
def lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
lowerCamelCase__ : Dict = self.dummy_unet
lowerCamelCase__ : Union[str, Any] = self.dummy_movq
lowerCamelCase__ : Optional[Any] = {
"num_train_timesteps": 1000,
"beta_schedule": "linear",
"beta_start": 0.0_0_0_8_5,
"beta_end": 0.0_1_2,
"clip_sample": False,
"set_alpha_to_one": False,
"steps_offset": 0,
"prediction_type": "epsilon",
"thresholding": False,
}
lowerCamelCase__ : List[Any] = DDIMScheduler(**__lowerCamelCase )
lowerCamelCase__ : Dict = {
"unet": unet,
"scheduler": scheduler,
"movq": movq,
}
return components
def lowerCAmelCase ( self : List[str] , __lowerCamelCase : str , __lowerCamelCase : Union[str, Any]=0 ):
'''simple docstring'''
lowerCamelCase__ : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
lowerCamelCase__ : Union[str, Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(
__lowerCamelCase )
# create init_image
lowerCamelCase__ : List[str] = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
lowerCamelCase__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowerCamelCase__ : Optional[Any] = Image.fromarray(np.uinta(__lowerCamelCase ) ).convert("RGB" ).resize((256, 256) )
# create hint
lowerCamelCase__ : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )
if str(__lowerCamelCase ).startswith("mps" ):
lowerCamelCase__ : List[str] = torch.manual_seed(__lowerCamelCase )
else:
lowerCamelCase__ : str = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase )
lowerCamelCase__ : str = {
"image": init_image,
"image_embeds": image_embeds,
"negative_image_embeds": negative_image_embeds,
"hint": hint,
"generator": generator,
"height": 64,
"width": 64,
"num_inference_steps": 10,
"guidance_scale": 7.0,
"strength": 0.2,
"output_type": "np",
}
return inputs
def lowerCAmelCase ( self : Any ):
'''simple docstring'''
lowerCamelCase__ : Any = "cpu"
lowerCamelCase__ : Any = self.get_dummy_components()
lowerCamelCase__ : Union[str, Any] = self.pipeline_class(**__lowerCamelCase )
lowerCamelCase__ : str = pipe.to(__lowerCamelCase )
pipe.set_progress_bar_config(disable=__lowerCamelCase )
lowerCamelCase__ : str = pipe(**self.get_dummy_inputs(__lowerCamelCase ) )
lowerCamelCase__ : List[str] = output.images
lowerCamelCase__ : int = pipe(
**self.get_dummy_inputs(__lowerCamelCase ) , return_dict=__lowerCamelCase , )[0]
lowerCamelCase__ : Optional[Any] = image[0, -3:, -3:, -1]
lowerCamelCase__ : Optional[int] = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
lowerCamelCase__ : Any = np.array(
[0.5_4_9_8_5_0_3_4, 0.5_5_5_0_9_3_6_5, 0.5_2_5_6_1_5_0_4, 0.5_5_7_0_4_9_4, 0.5_5_9_3_8_1_8, 0.5_2_6_3_9_7_9, 0.5_0_2_8_5_6_4_3, 0.5_0_6_9_8_4_6, 0.5_1_1_9_6_7_3_6] )
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 _lowercase ( unittest.TestCase):
"""simple docstring"""
def lowerCAmelCase ( self : Dict ):
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowerCAmelCase ( self : int ):
'''simple docstring'''
lowerCamelCase__ : Dict = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy" )
lowerCamelCase__ : Tuple = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" )
lowerCamelCase__ : List[str] = init_image.resize((512, 512) )
lowerCamelCase__ : Optional[Any] = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/kandinskyv22/hint_image_cat.png" )
lowerCamelCase__ : Optional[Any] = torch.from_numpy(np.array(__lowerCamelCase ) ).float() / 2_5_5.0
lowerCamelCase__ : Optional[Any] = hint.permute(2 , 0 , 1 ).unsqueeze(0 )
lowerCamelCase__ : Optional[Any] = "A robot, 4k photo"
lowerCamelCase__ : str = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained(
"kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa )
pipe_prior.to(__lowerCamelCase )
lowerCamelCase__ : int = KandinskyVaaControlnetImgaImgPipeline.from_pretrained(
"kandinsky-community/kandinsky-2-2-controlnet-depth" , torch_dtype=torch.floataa )
lowerCamelCase__ : List[Any] = pipeline.to(__lowerCamelCase )
pipeline.set_progress_bar_config(disable=__lowerCamelCase )
lowerCamelCase__ : str = torch.Generator(device="cpu" ).manual_seed(0 )
lowerCamelCase__ , lowerCamelCase__ : List[str] = pipe_prior(
__lowerCamelCase , image=__lowerCamelCase , strength=0.8_5 , generator=__lowerCamelCase , negative_prompt="" , ).to_tuple()
lowerCamelCase__ : Dict = pipeline(
image=__lowerCamelCase , image_embeds=__lowerCamelCase , negative_image_embeds=__lowerCamelCase , hint=__lowerCamelCase , generator=__lowerCamelCase , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type="np" , )
lowerCamelCase__ : List[Any] = output.images[0]
assert image.shape == (512, 512, 3)
assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
| 5 |
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
OpenAIGPTConfig,
OpenAIGPTDoubleHeadsModel,
OpenAIGPTForSequenceClassification,
OpenAIGPTLMHeadModel,
OpenAIGPTModel,
)
class _lowercase :
"""simple docstring"""
def __init__( self : Dict , __lowerCamelCase : str , __lowerCamelCase : Optional[int]=13 , __lowerCamelCase : List[str]=7 , __lowerCamelCase : Tuple=True , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : List[str]=True , __lowerCamelCase : Union[str, Any]=99 , __lowerCamelCase : List[Any]=32 , __lowerCamelCase : List[Any]=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : Optional[int]=37 , __lowerCamelCase : List[str]="gelu" , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : int=0.1 , __lowerCamelCase : List[str]=512 , __lowerCamelCase : Optional[Any]=16 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : str=0.0_2 , __lowerCamelCase : List[str]=3 , __lowerCamelCase : Tuple=4 , __lowerCamelCase : Optional[int]=None , ):
'''simple docstring'''
lowerCamelCase__ : Tuple = parent
lowerCamelCase__ : int = batch_size
lowerCamelCase__ : List[Any] = seq_length
lowerCamelCase__ : Union[str, Any] = is_training
lowerCamelCase__ : Any = use_token_type_ids
lowerCamelCase__ : Union[str, Any] = use_labels
lowerCamelCase__ : List[str] = vocab_size
lowerCamelCase__ : Union[str, Any] = hidden_size
lowerCamelCase__ : List[Any] = num_hidden_layers
lowerCamelCase__ : Optional[Any] = num_attention_heads
lowerCamelCase__ : Any = intermediate_size
lowerCamelCase__ : str = hidden_act
lowerCamelCase__ : str = hidden_dropout_prob
lowerCamelCase__ : Any = attention_probs_dropout_prob
lowerCamelCase__ : List[str] = max_position_embeddings
lowerCamelCase__ : Optional[int] = type_vocab_size
lowerCamelCase__ : List[Any] = type_sequence_label_size
lowerCamelCase__ : List[str] = initializer_range
lowerCamelCase__ : List[str] = num_labels
lowerCamelCase__ : List[Any] = num_choices
lowerCamelCase__ : Optional[Any] = scope
lowerCamelCase__ : List[Any] = self.vocab_size - 1
def lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
lowerCamelCase__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowerCamelCase__ : Optional[Any] = None
if self.use_token_type_ids:
lowerCamelCase__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
lowerCamelCase__ : Any = None
lowerCamelCase__ : str = None
lowerCamelCase__ : str = None
if self.use_labels:
lowerCamelCase__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowerCamelCase__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
lowerCamelCase__ : Dict = ids_tensor([self.batch_size] , self.num_choices )
lowerCamelCase__ : Union[str, Any] = OpenAIGPTConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , )
lowerCamelCase__ : Optional[int] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 )
return (
config,
input_ids,
head_mask,
token_type_ids,
sequence_labels,
token_labels,
choice_labels,
)
def lowerCAmelCase ( self : str , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : int , *__lowerCamelCase : List[Any] ):
'''simple docstring'''
lowerCamelCase__ : Optional[int] = OpenAIGPTModel(config=__lowerCamelCase )
model.to(__lowerCamelCase )
model.eval()
lowerCamelCase__ : Tuple = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , head_mask=__lowerCamelCase )
lowerCamelCase__ : str = model(__lowerCamelCase , token_type_ids=__lowerCamelCase )
lowerCamelCase__ : Optional[int] = model(__lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowerCAmelCase ( self : str , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , *__lowerCamelCase : Optional[int] ):
'''simple docstring'''
lowerCamelCase__ : Tuple = OpenAIGPTLMHeadModel(__lowerCamelCase )
model.to(__lowerCamelCase )
model.eval()
lowerCamelCase__ : List[str] = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase ( self : Dict , __lowerCamelCase : Any , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , *__lowerCamelCase : Tuple ):
'''simple docstring'''
lowerCamelCase__ : List[Any] = OpenAIGPTDoubleHeadsModel(__lowerCamelCase )
model.to(__lowerCamelCase )
model.eval()
lowerCamelCase__ : Optional[Any] = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase )
self.parent.assertEqual(result.loss.shape , () )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase ( self : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] , *__lowerCamelCase : Optional[int] ):
'''simple docstring'''
lowerCamelCase__ : Dict = self.num_labels
lowerCamelCase__ : Tuple = OpenAIGPTForSequenceClassification(__lowerCamelCase )
model.to(__lowerCamelCase )
model.eval()
lowerCamelCase__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowerCamelCase__ : List[str] = model(__lowerCamelCase , token_type_ids=__lowerCamelCase , labels=__lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
lowerCamelCase__ : str = self.prepare_config_and_inputs()
(
(
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) , (
lowerCamelCase__
) ,
) : Any = config_and_inputs
lowerCamelCase__ : Union[str, Any] = {
"input_ids": input_ids,
"token_type_ids": token_type_ids,
"head_mask": head_mask,
}
return config, inputs_dict
@require_torch
class _lowercase ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase):
"""simple docstring"""
A__ = (
(OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
if is_torch_available()
else ()
)
A__ = (
(OpenAIGPTLMHeadModel,) if is_torch_available() else ()
) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
A__ = (
{
"feature-extraction": OpenAIGPTModel,
"text-classification": OpenAIGPTForSequenceClassification,
"text-generation": OpenAIGPTLMHeadModel,
"zero-shot": OpenAIGPTForSequenceClassification,
}
if is_torch_available()
else {}
)
def lowerCAmelCase ( self : List[str] , __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] ):
'''simple docstring'''
if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
# `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
# tiny config could not be created.
return True
return False
def lowerCAmelCase ( self : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ):
'''simple docstring'''
lowerCamelCase__ : Tuple = super()._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase )
if return_labels:
if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
lowerCamelCase__ : Optional[Any] = torch.zeros(
(self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=__lowerCamelCase , )
lowerCamelCase__ : Tuple = inputs_dict["labels"]
lowerCamelCase__ : Any = inputs_dict["labels"]
lowerCamelCase__ : Any = torch.zeros(
(self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=__lowerCamelCase , )
lowerCamelCase__ : Union[str, Any] = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__lowerCamelCase )
return inputs_dict
def lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
lowerCamelCase__ : Tuple = OpenAIGPTModelTester(self )
lowerCamelCase__ : Union[str, Any] = ConfigTester(self , config_class=__lowerCamelCase , n_embd=37 )
def lowerCAmelCase ( self : int ):
'''simple docstring'''
self.config_tester.run_common_tests()
def lowerCAmelCase ( self : Dict ):
'''simple docstring'''
lowerCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_openai_gpt_model(*__lowerCamelCase )
def lowerCAmelCase ( self : str ):
'''simple docstring'''
lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head_model(*__lowerCamelCase )
def lowerCAmelCase ( self : Dict ):
'''simple docstring'''
lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_double_lm_head_model(*__lowerCamelCase )
def lowerCAmelCase ( self : Optional[int] ):
'''simple docstring'''
lowerCamelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__lowerCamelCase )
@slow
def lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase__ : Any = OpenAIGPTModel.from_pretrained(__lowerCamelCase )
self.assertIsNotNone(__lowerCamelCase )
@require_torch
class _lowercase ( unittest.TestCase):
"""simple docstring"""
@slow
def lowerCAmelCase ( self : Any ):
'''simple docstring'''
lowerCamelCase__ : List[Any] = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" )
model.to(__lowerCamelCase )
lowerCamelCase__ : int = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=__lowerCamelCase ) # the president is
lowerCamelCase__ : Union[str, Any] = [
481,
4735,
544,
246,
963,
870,
762,
239,
244,
40477,
244,
249,
719,
881,
487,
544,
240,
244,
603,
481,
] # the president is a very good man. " \n " i\'m sure he is, " said the
lowerCamelCase__ : int = model.generate(__lowerCamelCase , do_sample=__lowerCamelCase )
self.assertListEqual(output_ids[0].tolist() , __lowerCamelCase )
| 5 | 1 |
import argparse
import requests
import torch
from PIL import Image
from torchvision.transforms import Compose, Normalize, Resize, ToTensor
from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor
def a__ ( lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =SwinaSRConfig()
if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url:
UpperCAmelCase_ =4
elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url:
UpperCAmelCase_ =4
UpperCAmelCase_ =4_8
UpperCAmelCase_ ="pixelshuffle_aux"
elif "Swin2SR_Lightweight_X2_64" in checkpoint_url:
UpperCAmelCase_ =[6, 6, 6, 6]
UpperCAmelCase_ =6_0
UpperCAmelCase_ =[6, 6, 6, 6]
UpperCAmelCase_ ="pixelshuffledirect"
elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url:
UpperCAmelCase_ =4
UpperCAmelCase_ ="nearest+conv"
elif "Swin2SR_Jpeg_dynamic" in checkpoint_url:
UpperCAmelCase_ =1
UpperCAmelCase_ =1
UpperCAmelCase_ =1_2_6
UpperCAmelCase_ =7
UpperCAmelCase_ =255.0
UpperCAmelCase_ =""
return config
def a__ ( lowercase__ , lowercase__ ):
'''simple docstring'''
if "patch_embed.proj" in name and "layers" not in name:
UpperCAmelCase_ =name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" )
if "patch_embed.norm" in name:
UpperCAmelCase_ =name.replace("patch_embed.norm" , "embeddings.patch_embeddings.layernorm" )
if "layers" in name:
UpperCAmelCase_ =name.replace("layers" , "encoder.stages" )
if "residual_group.blocks" in name:
UpperCAmelCase_ =name.replace("residual_group.blocks" , "layers" )
if "attn.proj" in name:
UpperCAmelCase_ =name.replace("attn.proj" , "attention.output.dense" )
if "attn" in name:
UpperCAmelCase_ =name.replace("attn" , "attention.self" )
if "norm1" in name:
UpperCAmelCase_ =name.replace("norm1" , "layernorm_before" )
if "norm2" in name:
UpperCAmelCase_ =name.replace("norm2" , "layernorm_after" )
if "mlp.fc1" in name:
UpperCAmelCase_ =name.replace("mlp.fc1" , "intermediate.dense" )
if "mlp.fc2" in name:
UpperCAmelCase_ =name.replace("mlp.fc2" , "output.dense" )
if "q_bias" in name:
UpperCAmelCase_ =name.replace("q_bias" , "query.bias" )
if "k_bias" in name:
UpperCAmelCase_ =name.replace("k_bias" , "key.bias" )
if "v_bias" in name:
UpperCAmelCase_ =name.replace("v_bias" , "value.bias" )
if "cpb_mlp" in name:
UpperCAmelCase_ =name.replace("cpb_mlp" , "continuous_position_bias_mlp" )
if "patch_embed.proj" in name:
UpperCAmelCase_ =name.replace("patch_embed.proj" , "patch_embed.projection" )
if name == "norm.weight":
UpperCAmelCase_ ="layernorm.weight"
if name == "norm.bias":
UpperCAmelCase_ ="layernorm.bias"
if "conv_first" in name:
UpperCAmelCase_ =name.replace("conv_first" , "first_convolution" )
if (
"upsample" in name
or "conv_before_upsample" in name
or "conv_bicubic" in name
or "conv_up" in name
or "conv_hr" in name
or "conv_last" in name
or "aux" in name
):
# heads
if "conv_last" in name:
UpperCAmelCase_ =name.replace("conv_last" , "final_convolution" )
if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]:
if "conv_before_upsample.0" in name:
UpperCAmelCase_ =name.replace("conv_before_upsample.0" , "conv_before_upsample" )
if "upsample.0" in name:
UpperCAmelCase_ =name.replace("upsample.0" , "upsample.convolution_0" )
if "upsample.2" in name:
UpperCAmelCase_ =name.replace("upsample.2" , "upsample.convolution_1" )
UpperCAmelCase_ ="upsample." + name
elif config.upsampler == "pixelshuffledirect":
UpperCAmelCase_ =name.replace("upsample.0.weight" , "upsample.conv.weight" )
UpperCAmelCase_ =name.replace("upsample.0.bias" , "upsample.conv.bias" )
else:
pass
else:
UpperCAmelCase_ ="swin2sr." + name
return name
def a__ ( lowercase__ , lowercase__ ):
'''simple docstring'''
for key in orig_state_dict.copy().keys():
UpperCAmelCase_ =orig_state_dict.pop(lowercase__ )
if "qkv" in key:
UpperCAmelCase_ =key.split("." )
UpperCAmelCase_ =int(key_split[1] )
UpperCAmelCase_ =int(key_split[4] )
UpperCAmelCase_ =config.embed_dim
if "weight" in key:
UpperCAmelCase_ =val[:dim, :]
UpperCAmelCase_ =val[dim : dim * 2, :]
UpperCAmelCase_ =val[-dim:, :]
else:
UpperCAmelCase_ =val[:dim]
UpperCAmelCase_ =val[dim : dim * 2]
UpperCAmelCase_ =val[-dim:]
pass
else:
UpperCAmelCase_ =val
return orig_state_dict
def a__ ( lowercase__ , lowercase__ , lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =get_config(lowercase__ )
UpperCAmelCase_ =SwinaSRForImageSuperResolution(lowercase__ )
model.eval()
UpperCAmelCase_ =torch.hub.load_state_dict_from_url(lowercase__ , map_location="cpu" )
UpperCAmelCase_ =convert_state_dict(lowercase__ , lowercase__ )
UpperCAmelCase_ , UpperCAmelCase_ =model.load_state_dict(lowercase__ , strict=lowercase__ )
if len(lowercase__ ) > 0:
raise ValueError("Missing keys when converting: {}".format(lowercase__ ) )
for key in unexpected_keys:
if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key):
raise ValueError(F'Unexpected key {key} in state_dict' )
# verify values
UpperCAmelCase_ ="https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true"
UpperCAmelCase_ =Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ).convert("RGB" )
UpperCAmelCase_ =SwinaSRImageProcessor()
# pixel_values = processor(image, return_tensors="pt").pixel_values
UpperCAmelCase_ =1_2_6 if "Jpeg" in checkpoint_url else 2_5_6
UpperCAmelCase_ =Compose(
[
Resize((image_size, image_size) ),
ToTensor(),
Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ),
] )
UpperCAmelCase_ =transforms(lowercase__ ).unsqueeze(0 )
if config.num_channels == 1:
UpperCAmelCase_ =pixel_values[:, 0, :, :].unsqueeze(1 )
UpperCAmelCase_ =model(lowercase__ )
# assert values
if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url:
UpperCAmelCase_ =torch.Size([1, 3, 5_1_2, 5_1_2] )
UpperCAmelCase_ =torch.tensor(
[[-0.7087, -0.7138, -0.6721], [-0.8340, -0.8095, -0.7298], [-0.9149, -0.8414, -0.7940]] )
elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url:
UpperCAmelCase_ =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] )
UpperCAmelCase_ =torch.tensor(
[[-0.7775, -0.8105, -0.8933], [-0.7764, -0.8356, -0.9225], [-0.7976, -0.8686, -0.9579]] )
elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url:
# TODO values didn't match exactly here
UpperCAmelCase_ =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] )
UpperCAmelCase_ =torch.tensor(
[[-0.8035, -0.7504, -0.7491], [-0.8538, -0.8124, -0.7782], [-0.8804, -0.8651, -0.8493]] )
elif "Swin2SR_Lightweight_X2_64" in checkpoint_url:
UpperCAmelCase_ =torch.Size([1, 3, 5_1_2, 5_1_2] )
UpperCAmelCase_ =torch.tensor(
[[-0.7669, -0.8662, -0.8767], [-0.8810, -0.9962, -0.9820], [-0.9340, -1.0322, -1.1149]] )
elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url:
UpperCAmelCase_ =torch.Size([1, 3, 1_0_2_4, 1_0_2_4] )
UpperCAmelCase_ =torch.tensor(
[[-0.5238, -0.5557, -0.6321], [-0.6016, -0.5903, -0.6391], [-0.6244, -0.6334, -0.6889]] )
assert (
outputs.reconstruction.shape == expected_shape
), F'Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}'
assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , lowercase__ , atol=1E-3 )
print("Looks ok!" )
UpperCAmelCase_ ={
"https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth": (
"swin2SR-classical-sr-x2-64"
),
"https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth": (
"swin2SR-classical-sr-x4-64"
),
"https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth": (
"swin2SR-compressed-sr-x4-48"
),
"https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth": (
"swin2SR-lightweight-x2-64"
),
"https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth": (
"swin2SR-realworld-sr-x4-64-bsrgan-psnr"
),
}
UpperCAmelCase_ =url_to_name[checkpoint_url]
if pytorch_dump_folder_path is not None:
print(F'Saving model {model_name} to {pytorch_dump_folder_path}' )
model.save_pretrained(lowercase__ )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
processor.save_pretrained(lowercase__ )
if push_to_hub:
model.push_to_hub(F'caidas/{model_name}' )
processor.push_to_hub(F'caidas/{model_name}' )
if __name__ == "__main__":
__lowercase : Dict =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--checkpoint_url""",
default="""https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth""",
type=str,
help="""URL of the original Swin2SR 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."""
)
parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Whether to push the converted model to the hub.""")
__lowercase : str =parser.parse_args()
convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
| 54 |
import inspect
import unittest
from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DPTImageProcessor
class lowerCamelCase :
def __init__( self , lowercase__ , lowercase__=2 , lowercase__=3_2 , lowercase__=1_6 , lowercase__=3 , lowercase__=True , lowercase__=True , lowercase__=3_2 , lowercase__=4 , lowercase__=[0, 1, 2, 3] , lowercase__=4 , lowercase__=3_7 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=0.0_2 , lowercase__=3 , lowercase__=[1, 3_8_4, 2_4, 2_4] , lowercase__=True , lowercase__=None , ):
__UpperCAmelCase : Any = parent
__UpperCAmelCase : Tuple = batch_size
__UpperCAmelCase : Optional[int] = image_size
__UpperCAmelCase : Tuple = patch_size
__UpperCAmelCase : int = num_channels
__UpperCAmelCase : Optional[Any] = is_training
__UpperCAmelCase : Union[str, Any] = use_labels
__UpperCAmelCase : List[Any] = hidden_size
__UpperCAmelCase : Optional[Any] = num_hidden_layers
__UpperCAmelCase : Any = backbone_out_indices
__UpperCAmelCase : Union[str, Any] = num_attention_heads
__UpperCAmelCase : Dict = intermediate_size
__UpperCAmelCase : Dict = hidden_act
__UpperCAmelCase : Dict = hidden_dropout_prob
__UpperCAmelCase : List[Any] = attention_probs_dropout_prob
__UpperCAmelCase : List[Any] = initializer_range
__UpperCAmelCase : Union[str, Any] = num_labels
__UpperCAmelCase : List[Any] = backbone_featmap_shape
__UpperCAmelCase : Any = scope
__UpperCAmelCase : Optional[int] = is_hybrid
# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
__UpperCAmelCase : Optional[Any] = (image_size // patch_size) ** 2
__UpperCAmelCase : Any = num_patches + 1
def A( self):
__UpperCAmelCase : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__UpperCAmelCase : List[str] = None
if self.use_labels:
__UpperCAmelCase : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels)
__UpperCAmelCase : Dict = self.get_config()
return config, pixel_values, labels
def A( self):
__UpperCAmelCase : Dict = {
'''global_padding''': '''same''',
'''layer_type''': '''bottleneck''',
'''depths''': [3, 4, 9],
'''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
'''embedding_dynamic_padding''': True,
'''hidden_sizes''': [9_6, 1_9_2, 3_8_4, 7_6_8],
'''num_groups''': 2,
}
return DPTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase__ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=lowercase__ , backbone_featmap_shape=self.backbone_featmap_shape , )
def A( self , lowercase__ , lowercase__ , lowercase__):
__UpperCAmelCase : List[str] = DPTModel(config=lowercase__)
model.to(lowercase__)
model.eval()
__UpperCAmelCase : Dict = model(lowercase__)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def A( self , lowercase__ , lowercase__ , lowercase__):
__UpperCAmelCase : List[str] = self.num_labels
__UpperCAmelCase : Optional[Any] = DPTForDepthEstimation(lowercase__)
model.to(lowercase__)
model.eval()
__UpperCAmelCase : str = model(lowercase__)
self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size))
def A( self , lowercase__ , lowercase__ , lowercase__):
__UpperCAmelCase : Tuple = self.num_labels
__UpperCAmelCase : Optional[int] = DPTForSemanticSegmentation(lowercase__)
model.to(lowercase__)
model.eval()
__UpperCAmelCase : str = model(lowercase__ , labels=lowercase__)
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size))
def A( self):
__UpperCAmelCase : int = self.prepare_config_and_inputs()
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Optional[int] = config_and_inputs
__UpperCAmelCase : Union[str, Any] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
_lowerCAmelCase : Union[str, Any] = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
_lowerCAmelCase : Optional[int] = (
{
'''depth-estimation''': DPTForDepthEstimation,
'''feature-extraction''': DPTModel,
'''image-segmentation''': DPTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
_lowerCAmelCase : Any = False
_lowerCAmelCase : str = False
_lowerCAmelCase : List[Any] = False
def A( self):
__UpperCAmelCase : Any = DPTModelTester(self)
__UpperCAmelCase : str = ConfigTester(self , config_class=lowercase__ , has_text_modality=lowercase__ , hidden_size=3_7)
def A( self):
self.config_tester.run_common_tests()
@unittest.skip(reason='''DPT does not use inputs_embeds''')
def A( self):
pass
def A( self):
__UpperCAmelCase , __UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__UpperCAmelCase : str = model_class(lowercase__)
self.assertIsInstance(model.get_input_embeddings() , (nn.Module))
__UpperCAmelCase : Tuple = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(lowercase__ , nn.Linear))
def A( self):
__UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__UpperCAmelCase : Optional[int] = model_class(lowercase__)
__UpperCAmelCase : int = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__UpperCAmelCase : List[str] = [*signature.parameters.keys()]
__UpperCAmelCase : str = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , lowercase__)
def A( self):
__UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowercase__)
def A( self):
__UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_depth_estimation(*lowercase__)
def A( self):
__UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*lowercase__)
def A( self):
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
__UpperCAmelCase , __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCAmelCase : Any = True
if model_class in get_values(lowercase__):
continue
__UpperCAmelCase : List[Any] = model_class(lowercase__)
model.to(lowercase__)
model.train()
__UpperCAmelCase : Any = self._prepare_for_class(lowercase__ , lowercase__ , return_labels=lowercase__)
__UpperCAmelCase : Any = model(**lowercase__).loss
loss.backward()
def A( self):
for model_class in self.all_model_classes:
if model_class.__name__ == "DPTForDepthEstimation":
continue
__UpperCAmelCase , __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCAmelCase : Optional[int] = False
__UpperCAmelCase : str = True
if model_class in get_values(lowercase__) or not model_class.supports_gradient_checkpointing:
continue
__UpperCAmelCase : Tuple = model_class(lowercase__)
model.to(lowercase__)
model.gradient_checkpointing_enable()
model.train()
__UpperCAmelCase : Tuple = self._prepare_for_class(lowercase__ , lowercase__ , return_labels=lowercase__)
__UpperCAmelCase : Union[str, Any] = model(**lowercase__).loss
loss.backward()
def A( self):
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCAmelCase : List[Any] = _config_zero_init(lowercase__)
for model_class in self.all_model_classes:
__UpperCAmelCase : Tuple = model_class(config=lowercase__)
# Skip the check for the backbone
__UpperCAmelCase : List[Any] = []
for name, module in model.named_modules():
if module.__class__.__name__ == "DPTViTHybridEmbeddings":
__UpperCAmelCase : Optional[Any] = [F"{name}.{key}" for key in module.state_dict().keys()]
break
for name, param in model.named_parameters():
if param.requires_grad:
if name in backbone_params:
continue
self.assertIn(
((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
def A( self):
pass
@slow
def A( self):
for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
__UpperCAmelCase : Optional[int] = DPTModel.from_pretrained(lowercase__)
self.assertIsNotNone(lowercase__)
def A( self):
# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
__UpperCAmelCase , __UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCAmelCase : List[str] = '''add'''
with self.assertRaises(lowercase__):
__UpperCAmelCase : Optional[Any] = DPTForDepthEstimation(lowercase__)
def __SCREAMING_SNAKE_CASE ( ) -> Dict:
'''simple docstring'''
__UpperCAmelCase : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
@slow
class lowerCamelCase ( unittest.TestCase ):
def A( self):
__UpperCAmelCase : str = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''')
__UpperCAmelCase : str = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''').to(lowercase__)
__UpperCAmelCase : List[str] = prepare_img()
__UpperCAmelCase : Tuple = image_processor(images=lowercase__ , return_tensors='''pt''').to(lowercase__)
# forward pass
with torch.no_grad():
__UpperCAmelCase : List[Any] = model(**lowercase__)
__UpperCAmelCase : str = outputs.predicted_depth
# verify the predicted depth
__UpperCAmelCase : Union[str, Any] = torch.Size((1, 3_8_4, 3_8_4))
self.assertEqual(predicted_depth.shape , lowercase__)
__UpperCAmelCase : List[str] = torch.tensor(
[[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]]).to(lowercase__)
self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , lowercase__ , atol=1e-4))
| 462 | 0 |
"""simple docstring"""
class __lowercase:
'''simple docstring'''
def __init__( self , __a , __a , __a ):
__lowerCamelCase : List[Any] = name
__lowerCamelCase : str = value
__lowerCamelCase : Dict = weight
def __repr__( self ):
return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})'''
def snake_case_ ( self ):
return self.value
def snake_case_ ( self ):
return self.name
def snake_case_ ( self ):
return self.weight
def snake_case_ ( self ):
return self.value / self.weight
def UpperCAmelCase ( A__: Union[str, Any] , A__: List[Any] , A__: List[Any] ) -> Optional[int]:
__lowerCamelCase : int = []
for i in range(len(__lowerCAmelCase ) ):
menu.append(Things(name[i] , value[i] , weight[i] ) )
return menu
def UpperCAmelCase ( A__: Union[str, Any] , A__: str , A__: int ) -> Any:
__lowerCamelCase : Optional[Any] = sorted(__lowerCAmelCase , key=__lowerCAmelCase , reverse=__lowerCAmelCase )
__lowerCamelCase : int = []
__lowerCamelCase , __lowerCamelCase : int = 0.0, 0.0
for i in range(len(__lowerCAmelCase ) ):
if (total_cost + items_copy[i].get_weight()) <= max_cost:
result.append(items_copy[i] )
total_cost += items_copy[i].get_weight()
total_value += items_copy[i].get_value()
return (result, total_value)
def UpperCAmelCase ( ) -> List[str]:
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| 712 |
"""simple docstring"""
def UpperCAmelCase ( A__: Dict ) -> Optional[int]:
stooge(A__ , 0 , len(A__ ) - 1 )
return arr
def UpperCAmelCase ( A__: Dict , A__: List[str] , A__: Optional[int] ) -> Any:
if i >= h:
return
# If first element is smaller than the last then swap them
if arr[i] > arr[h]:
__lowerCamelCase , __lowerCamelCase : Dict = arr[h], arr[i]
# If there are more than 2 elements in the array
if h - i + 1 > 2:
__lowerCamelCase : str = (int)((h - i + 1) / 3 )
# Recursively sort first 2/3 elements
stooge(A__ , A__ , (h - t) )
# Recursively sort last 2/3 elements
stooge(A__ , i + t , (A__) )
# Recursively sort first 2/3 elements
stooge(A__ , A__ , (h - t) )
if __name__ == "__main__":
a_ : Tuple = input('''Enter numbers separated by a comma:\n''').strip()
a_ : Optional[Any] = [int(item) for item in user_input.split(''',''')]
print(stooge_sort(unsorted))
| 263 | 0 |
from __future__ import annotations
import unittest
from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFFunnelBaseModel,
TFFunnelForMaskedLM,
TFFunnelForMultipleChoice,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForSequenceClassification,
TFFunnelForTokenClassification,
TFFunnelModel,
)
class __UpperCamelCase :
'''simple docstring'''
def __init__( self , lowerCamelCase__ , lowerCamelCase__=1_3 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=9_9 , lowerCamelCase__=[1, 1, 2] , lowerCamelCase__=1 , lowerCamelCase__=3_2 , lowerCamelCase__=4 , lowerCamelCase__=8 , lowerCamelCase__=3_7 , lowerCamelCase__="gelu_new" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=0.0 , lowerCamelCase__=5_1_2 , lowerCamelCase__=3 , lowerCamelCase__=0.02 , lowerCamelCase__=3 , lowerCamelCase__=4 , lowerCamelCase__=None , lowerCamelCase__=False , ):
UpperCAmelCase__: Tuple = parent
UpperCAmelCase__: int = batch_size
UpperCAmelCase__: Optional[Any] = seq_length
UpperCAmelCase__: Union[str, Any] = is_training
UpperCAmelCase__: List[str] = use_input_mask
UpperCAmelCase__: str = use_token_type_ids
UpperCAmelCase__: Union[str, Any] = use_labels
UpperCAmelCase__: Union[str, Any] = vocab_size
UpperCAmelCase__: Optional[int] = block_sizes
UpperCAmelCase__: Dict = num_decoder_layers
UpperCAmelCase__: List[Any] = d_model
UpperCAmelCase__: int = n_head
UpperCAmelCase__: Optional[Any] = d_head
UpperCAmelCase__: Optional[int] = d_inner
UpperCAmelCase__: int = hidden_act
UpperCAmelCase__: Dict = hidden_dropout
UpperCAmelCase__: int = attention_dropout
UpperCAmelCase__: Tuple = activation_dropout
UpperCAmelCase__: Any = max_position_embeddings
UpperCAmelCase__: str = type_vocab_size
UpperCAmelCase__: Optional[int] = 2
UpperCAmelCase__: List[Any] = num_labels
UpperCAmelCase__: Optional[Any] = num_choices
UpperCAmelCase__: Union[str, Any] = scope
UpperCAmelCase__: Tuple = initializer_std
# Used in the tests to check the size of the first attention layer
UpperCAmelCase__: List[str] = n_head
# Used in the tests to check the size of the first hidden state
UpperCAmelCase__: Any = self.d_model
# Used in the tests to check the number of output hidden states/attentions
UpperCAmelCase__: List[Any] = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers)
# FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
# the last hidden state of the first block (which is the first hidden state of the decoder).
if not base:
UpperCAmelCase__: Optional[Any] = self.num_hidden_layers + 2
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
UpperCAmelCase__: Optional[int] = None
if self.use_input_mask:
UpperCAmelCase__: Optional[int] = random_attention_mask([self.batch_size, self.seq_length] )
UpperCAmelCase__: Any = None
if self.use_token_type_ids:
UpperCAmelCase__: Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
UpperCAmelCase__: int = None
UpperCAmelCase__: Optional[int] = None
UpperCAmelCase__: Optional[int] = None
if self.use_labels:
UpperCAmelCase__: List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCAmelCase__: Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCAmelCase__: Optional[Any] = ids_tensor([self.batch_size] , self.num_choices )
UpperCAmelCase__: Optional[Any] = FunnelConfig(
vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , )
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
)
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: int = TFFunnelModel(config=_snake_case )
UpperCAmelCase__: Union[str, Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase__: Optional[Any] = model(_snake_case )
UpperCAmelCase__: List[str] = [input_ids, input_mask]
UpperCAmelCase__: Dict = model(_snake_case )
UpperCAmelCase__: str = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
UpperCAmelCase__: Dict = False
UpperCAmelCase__: Union[str, Any] = TFFunnelModel(config=_snake_case )
UpperCAmelCase__: Tuple = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
UpperCAmelCase__: Tuple = False
UpperCAmelCase__: Any = TFFunnelModel(config=_snake_case )
UpperCAmelCase__: Dict = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: Union[str, Any] = TFFunnelBaseModel(config=_snake_case )
UpperCAmelCase__: Optional[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase__: int = model(_snake_case )
UpperCAmelCase__: Optional[int] = [input_ids, input_mask]
UpperCAmelCase__: List[Any] = model(_snake_case )
UpperCAmelCase__: Any = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) )
UpperCAmelCase__: int = False
UpperCAmelCase__: Dict = TFFunnelBaseModel(config=_snake_case )
UpperCAmelCase__: Tuple = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) )
UpperCAmelCase__: Optional[int] = False
UpperCAmelCase__: str = TFFunnelBaseModel(config=_snake_case )
UpperCAmelCase__: str = model(_snake_case )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) )
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: Union[str, Any] = TFFunnelForPreTraining(config=_snake_case )
UpperCAmelCase__: Union[str, Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase__: Optional[Any] = model(_snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) )
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: List[Any] = TFFunnelForMaskedLM(config=_snake_case )
UpperCAmelCase__: Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase__: Optional[int] = model(_snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: Optional[Any] = self.num_labels
UpperCAmelCase__: Dict = TFFunnelForSequenceClassification(config=_snake_case )
UpperCAmelCase__: Tuple = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase__: Union[str, Any] = model(_snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: Dict = self.num_choices
UpperCAmelCase__: Tuple = TFFunnelForMultipleChoice(config=_snake_case )
UpperCAmelCase__: Dict = tf.tile(tf.expand_dims(_snake_case , 1 ) , (1, self.num_choices, 1) )
UpperCAmelCase__: List[Any] = tf.tile(tf.expand_dims(_snake_case , 1 ) , (1, self.num_choices, 1) )
UpperCAmelCase__: Any = tf.tile(tf.expand_dims(_snake_case , 1 ) , (1, self.num_choices, 1) )
UpperCAmelCase__: Optional[int] = {
'''input_ids''': multiple_choice_inputs_ids,
'''attention_mask''': multiple_choice_input_mask,
'''token_type_ids''': multiple_choice_token_type_ids,
}
UpperCAmelCase__: Dict = model(_snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: Tuple = self.num_labels
UpperCAmelCase__: Any = TFFunnelForTokenClassification(config=_snake_case )
UpperCAmelCase__: Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase__: int = model(_snake_case )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ):
UpperCAmelCase__: Optional[Any] = TFFunnelForQuestionAnswering(config=_snake_case )
UpperCAmelCase__: Optional[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
UpperCAmelCase__: Optional[Any] = model(_snake_case )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Dict = self.prepare_config_and_inputs()
(
UpperCAmelCase__
): Dict = config_and_inputs
UpperCAmelCase__: List[Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_tf
class __UpperCamelCase ( a_ ,a_ ,unittest.TestCase ):
'''simple docstring'''
__magic_name__ = (
(
TFFunnelModel,
TFFunnelForMaskedLM,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForTokenClassification,
)
if is_tf_available()
else ()
)
__magic_name__ = (
{
'feature-extraction': (TFFunnelBaseModel, TFFunnelModel),
'fill-mask': TFFunnelForMaskedLM,
'question-answering': TFFunnelForQuestionAnswering,
'text-classification': TFFunnelForSequenceClassification,
'token-classification': TFFunnelForTokenClassification,
'zero-shot': TFFunnelForSequenceClassification,
}
if is_tf_available()
else {}
)
__magic_name__ = False
__magic_name__ = False
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Union[str, Any] = TFFunnelModelTester(self )
UpperCAmelCase__: Any = ConfigTester(self , config_class=_snake_case )
def _UpperCAmelCase ( self ):
self.config_tester.run_common_tests()
def _UpperCAmelCase ( self ):
UpperCAmelCase__: str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_snake_case )
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*_snake_case )
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*_snake_case )
def _UpperCAmelCase ( self ):
UpperCAmelCase__: List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*_snake_case )
def _UpperCAmelCase ( self ):
UpperCAmelCase__: List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*_snake_case )
@require_tf
class __UpperCamelCase ( a_ ,unittest.TestCase ):
'''simple docstring'''
__magic_name__ = (
(TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
)
__magic_name__ = False
__magic_name__ = False
def _UpperCAmelCase ( self ):
UpperCAmelCase__: List[str] = TFFunnelModelTester(self , base=_snake_case )
UpperCAmelCase__: str = ConfigTester(self , config_class=_snake_case )
def _UpperCAmelCase ( self ):
self.config_tester.run_common_tests()
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_base_model(*_snake_case )
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*_snake_case )
def _UpperCAmelCase ( self ):
UpperCAmelCase__: Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*_snake_case ) | 113 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available
_UpperCAmelCase : Tuple = {
"""configuration_longt5""": ["""LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LongT5Config""", """LongT5OnnxConfig"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : List[str] = [
"""LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""LongT5EncoderModel""",
"""LongT5ForConditionalGeneration""",
"""LongT5Model""",
"""LongT5PreTrainedModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCAmelCase : List[str] = [
"""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
_UpperCAmelCase : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 683 | 0 |
from scipy.stats import spearmanr
import datasets
lowerCAmelCase__ = """
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.
Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.
The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""
lowerCAmelCase__ = """
Args:
predictions (`List[float]`): Predicted labels, as returned by a model.
references (`List[float]`): Ground truth labels.
return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
only the spearmanr score. Defaults to `False`.
Returns:
spearmanr (`float`): Spearman correlation coefficient.
p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
Example 1:
>>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
>>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
>>> print(results)
{'spearmanr': -0.7}
Example 2:
>>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
>>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
... predictions=[10, 9, 2.5, 6, 4],
... return_pvalue=True)
>>> print(results['spearmanr'])
-0.7
>>> print(round(results['spearmanr_pvalue'], 2))
0.19
"""
lowerCAmelCase__ = R"""\
@book{kokoska2000crc,
title={CRC standard probability and statistics tables and formulae},
author={Kokoska, Stephen and Zwillinger, Daniel},
year={2000},
publisher={Crc Press}
}
@article{2020SciPy-NMeth,
author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
Haberland, Matt and Reddy, Tyler and Cournapeau, David and
Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
Kern, Robert and Larson, Eric and Carey, C J and
Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
{VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
Harris, Charles R. and Archibald, Anne M. and
Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
{van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
Computing in Python}},
journal = {Nature Methods},
year = {2020},
volume = {17},
pages = {261--272},
adsurl = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowercase ( datasets.Metric ):
"""simple docstring"""
def A__ ( self):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'predictions': datasets.Value('float'),
'references': datasets.Value('float'),
}) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html'] , )
def A__ ( self , __snake_case , __snake_case , __snake_case=False):
_UpperCamelCase : Any = spearmanr(__snake_case , __snake_case)
if return_pvalue:
return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
else:
return {"spearmanr": results[0]}
| 648 |
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import SPIECE_UNDERLINE, is_sentencepiece_available
from transformers.models.speech_to_text import SpeechaTextTokenizer
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""")
if is_sentencepiece_available():
import sentencepiece as sp
lowerCAmelCase__ = 5
lowerCAmelCase__ = 1_0
@require_sentencepiece
@require_tokenizers
class lowercase ( _lowercase , unittest.TestCase ):
"""simple docstring"""
a__ = SpeechaTextTokenizer
a__ = False
a__ = True
def A__ ( self):
super().setUp()
_UpperCamelCase : Any = sp.SentencePieceProcessor()
spm_model.Load(__snake_case)
_UpperCamelCase : List[str] = ['<s>', '<pad>', '</s>', '<unk>']
vocab += [spm_model.IdToPiece(id_) for id_ in range(len(__snake_case))]
_UpperCamelCase : Dict = dict(zip(__snake_case , range(len(__snake_case))))
_UpperCamelCase : Tuple = Path(self.tmpdirname)
save_json(__snake_case , save_dir / VOCAB_FILES_NAMES['vocab_file'])
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(__snake_case , save_dir / VOCAB_FILES_NAMES['spm_file'])
_UpperCamelCase : int = SpeechaTextTokenizer.from_pretrained(self.tmpdirname)
tokenizer.save_pretrained(self.tmpdirname)
def A__ ( self):
_UpperCamelCase : str = '<pad>'
_UpperCamelCase : Dict = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__snake_case) , __snake_case)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__snake_case) , __snake_case)
def A__ ( self):
_UpperCamelCase : Optional[Any] = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , '<s>')
self.assertEqual(vocab_keys[1] , '<pad>')
self.assertEqual(vocab_keys[-1] , 'j')
self.assertEqual(len(__snake_case) , 10_01)
def A__ ( self):
self.assertEqual(self.get_tokenizer().vocab_size , 10_01)
def A__ ( self):
_UpperCamelCase : Any = SpeechaTextTokenizer.from_pretrained(self.tmpdirname)
_UpperCamelCase : List[str] = tokenizer.tokenize('This is a test')
self.assertListEqual(__snake_case , ['▁This', '▁is', '▁a', '▁t', 'est'])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__snake_case) , [2_89, 50, 14, 1_74, 3_86] , )
_UpperCamelCase : int = tokenizer.tokenize('I was born in 92000, and this is falsé.')
self.assertListEqual(
__snake_case , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , )
_UpperCamelCase : int = tokenizer.convert_tokens_to_ids(__snake_case)
self.assertListEqual(__snake_case , [12, 25, 88, 59, 28, 23, 11, 4, 6_06, 3_51, 3_51, 3_51, 7, 16, 70, 50, 76, 84, 10, 4, 8])
_UpperCamelCase : Tuple = tokenizer.convert_ids_to_tokens(__snake_case)
self.assertListEqual(
__snake_case , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , )
@slow
def A__ ( self):
# fmt: off
_UpperCamelCase : Optional[int] = {'input_ids': [[37_91, 7_97, 31, 11, 64, 7_97, 31, 24_29, 4_33, 12, 11_76, 12, 20, 7_86, 9_15, 1_42, 24_13, 2_40, 37, 32_38, 7_97, 31, 11, 35, 93, 9_15, 1_42, 24_13, 2_40, 37, 55_40, 5_67, 12_76, 93, 37, 6_10, 40, 62, 4_55, 6_57, 10_42, 1_23, 7_80, 1_77, 37, 3_09, 2_41, 12_98, 5_14, 20, 2_92, 27_37, 1_14, 24_69, 2_41, 85, 64, 3_02, 5_48, 5_28, 4_23, 4, 5_09, 4_06, 4_23, 37, 6_01, 4, 7_77, 3_02, 5_48, 5_28, 4_23, 2_84, 4, 33_88, 5_11, 4_59, 4, 35_55, 40, 3_21, 3_02, 7_05, 4, 33_88, 5_11, 5_83, 3_26, 5, 5, 5, 62, 33_10, 5_60, 1_77, 26_80, 2_17, 15_08, 32, 31, 8_53, 4_18, 64, 5_83, 5_11, 16_05, 62, 35, 93, 5_60, 1_77, 26_80, 2_17, 15_08, 15_21, 64, 5_83, 5_11, 5_19, 62, 20, 15_15, 7_64, 20, 1_49, 2_61, 56_25, 79_72, 20, 55_40, 5_67, 12_76, 93, 39_25, 16_75, 11, 15, 8_02, 79_72, 5_76, 2_17, 15_08, 11, 35, 93, 12_53, 24_41, 15, 2_89, 6_52, 31, 4_16, 3_21, 38_42, 1_15, 40, 9_11, 8, 4_76, 6_19, 4, 3_80, 1_42, 4_23, 3_35, 2_40, 35, 93, 2_64, 8, 11, 3_35, 5_69, 4_20, 1_63, 5, 2], [2_60, 5_48, 5_28, 4_23, 20, 4_51, 20, 26_81, 11_53, 34_34, 20, 55_40, 37, 5_67, 1_26, 12_53, 24_41, 33_76, 4_49, 2_10, 4_31, 15_63, 1_77, 7_67, 55_40, 11, 12_03, 4_72, 11, 29_53, 6_85, 2_85, 3_64, 7_06, 11_53, 20, 67_99, 20, 28_69, 20, 44_64, 1_26, 40, 24_29, 20, 10_40, 8_66, 26_64, 4_18, 20, 3_18, 20, 17_26, 1_86, 20, 2_65, 5_22, 35, 93, 21_91, 46_34, 20, 10_40, 12, 67_99, 15, 2_28, 23_56, 1_42, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_75, 26_66, 6_84, 15_82, 11_76, 12, 6_27, 1_49, 6_19, 20, 49_02, 5_63, 11, 20, 1_49, 2_61, 34_20, 23_56, 1_74, 1_42, 47_14, 1_31, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=__snake_case , model_name='facebook/s2t-small-mustc-en-de-st' , revision='a14f04cf0776c02f62a8cb800cf7909e15ea23ad' , )
@require_sentencepiece
class lowercase ( unittest.TestCase ):
"""simple docstring"""
a__ = "valhalla/s2t_mustc_multilinguial_medium"
a__ = "C'est trop cool"
a__ = "Esto es genial"
@classmethod
def A__ ( cls):
_UpperCamelCase : SpeechaTextTokenizer = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name)
return cls
def A__ ( self):
self.assertEqual(self.tokenizer.lang_code_to_id['pt'] , 4)
self.assertEqual(self.tokenizer.lang_code_to_id['ru'] , 6)
self.assertEqual(self.tokenizer.lang_code_to_id['it'] , 9)
self.assertEqual(self.tokenizer.lang_code_to_id['de'] , 11)
def A__ ( self):
self.assertEqual(self.tokenizer.vocab_size , 1_00_00)
def A__ ( self):
self.assertIn(__snake_case , self.tokenizer.all_special_ids)
_UpperCamelCase : Optional[int] = [ES_CODE, 4, 16_01, 47, 76_47, 2]
_UpperCamelCase : Tuple = self.tokenizer.decode(__snake_case , skip_special_tokens=__snake_case)
_UpperCamelCase : Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__snake_case)
self.assertEqual(__snake_case , __snake_case)
self.assertNotIn(self.tokenizer.eos_token , __snake_case)
def A__ ( self):
_UpperCamelCase : Any = 'fr'
_UpperCamelCase : List[Any] = self.tokenizer(self.french_text).input_ids
self.assertEqual(encoded[0] , __snake_case)
self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id)
def A__ ( self):
_UpperCamelCase : Union[str, Any] = 'fr'
self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE])
_UpperCamelCase : List[str] = 'es'
self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE])
| 648 | 1 |
"""simple docstring"""
def _A ( __lowercase , __lowercase ):
"""simple docstring"""
return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2
def _A ( __lowercase , __lowercase=0 ):
"""simple docstring"""
return sorted(_lowerCAmelCase , key=lambda __lowercase : x[column] )
def _A ( __lowercase , __lowercase , __lowercase=float("""inf""" ) ):
"""simple docstring"""
for i in range(points_counts - 1 ):
for j in range(i + 1 , _lowerCAmelCase ):
lowerCamelCase__ = euclidean_distance_sqr(points[i] , points[j] )
if current_dis < min_dis:
lowerCamelCase__ = current_dis
return min_dis
def _A ( __lowercase , __lowercase , __lowercase=float("""inf""" ) ):
"""simple docstring"""
for i in range(min(6 , points_counts - 1 ) , _lowerCAmelCase ):
for j in range(max(0 , i - 6 ) , _lowerCAmelCase ):
lowerCamelCase__ = euclidean_distance_sqr(points[i] , points[j] )
if current_dis < min_dis:
lowerCamelCase__ = current_dis
return min_dis
def _A ( __lowercase , __lowercase , __lowercase ):
"""simple docstring"""
if points_counts <= 3:
return dis_between_closest_pair(_lowerCAmelCase , _lowerCAmelCase )
# recursion
lowerCamelCase__ = points_counts // 2
lowerCamelCase__ = closest_pair_of_points_sqr(
_lowerCAmelCase , points_sorted_on_y[:mid] , _lowerCAmelCase )
lowerCamelCase__ = closest_pair_of_points_sqr(
_lowerCAmelCase , points_sorted_on_y[mid:] , points_counts - mid )
lowerCamelCase__ = min(_lowerCAmelCase , _lowerCAmelCase )
lowerCamelCase__ = []
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis:
cross_strip.append(_lowerCAmelCase )
lowerCamelCase__ = dis_between_closest_in_strip(
_lowerCAmelCase , len(_lowerCAmelCase ) , _lowerCAmelCase )
return min(_lowerCAmelCase , _lowerCAmelCase )
def _A ( __lowercase , __lowercase ):
"""simple docstring"""
lowerCamelCase__ = column_based_sort(_lowerCAmelCase , column=0 )
lowerCamelCase__ = column_based_sort(_lowerCAmelCase , column=1 )
return (
closest_pair_of_points_sqr(
_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
) ** 0.5
if __name__ == "__main__":
__magic_name__ = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print("""Distance:""", closest_pair_of_points(points, len(points)))
| 129 |
'''simple docstring'''
import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional
from torch.utils.data import ConcatDataset
import transformers
from transformers import (
CONFIG_MAPPING,
MODEL_WITH_LM_HEAD_MAPPING,
AutoConfig,
AutoModelWithLMHead,
AutoTokenizer,
DataCollatorForLanguageModeling,
DataCollatorForPermutationLanguageModeling,
DataCollatorForWholeWordMask,
HfArgumentParser,
LineByLineTextDataset,
LineByLineWithRefDataset,
PreTrainedTokenizer,
TextDataset,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import is_main_process
__a = logging.getLogger(__name__)
__a = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
__a = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowercase = field(
default=_a , metadata={
"help": (
"The model checkpoint for weights initialization. Leave None if you want to train a model from"
" scratch."
)
} , )
lowercase = field(
default=_a , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_a )} , )
lowercase = field(
default=_a , metadata={"help": "Pretrained config name or path if not the same as model_name"} )
lowercase = field(
default=_a , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
lowercase = field(
default=_a , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , )
@dataclass
class UpperCAmelCase_ :
"""simple docstring"""
lowercase = field(
default=_a , metadata={"help": "The input training data file (a text file)."} )
lowercase = field(
default=_a , metadata={
"help": (
"The input training data files (multiple files in glob format). "
"Very often splitting large files to smaller files can prevent tokenizer going out of memory"
)
} , )
lowercase = field(
default=_a , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , )
lowercase = field(
default=_a , metadata={"help": "An optional input train ref data file for whole word mask in Chinese."} , )
lowercase = field(
default=_a , metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."} , )
lowercase = field(
default=_a , metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."} , )
lowercase = field(
default=_a , metadata={"help": "Train with masked-language modeling loss instead of language modeling."} )
lowercase = field(default=_a , metadata={"help": "Whether ot not to use whole word mask."} )
lowercase = field(
default=0.15 , metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} )
lowercase = field(
default=1 / 6 , metadata={
"help": (
"Ratio of length of a span of masked tokens to surrounding context length for permutation language"
" modeling."
)
} , )
lowercase = field(
default=5 , metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."} )
lowercase = field(
default=-1 , metadata={
"help": (
"Optional input sequence length after tokenization."
"The training dataset will be truncated in block of this size for training."
"Default to the model max input length for single sentence inputs (take into account special tokens)."
)
} , )
lowercase = field(
default=_a , metadata={"help": "Overwrite the cached training and evaluation sets"} )
def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = False , _lowerCAmelCase = None , ) -> Tuple:
def _dataset(_lowerCAmelCase , _lowerCAmelCase=None ):
if args.line_by_line:
if ref_path is not None:
if not args.whole_word_mask or not args.mlm:
raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" )
return LineByLineWithRefDataset(
tokenizer=_lowerCAmelCase , file_path=_lowerCAmelCase , block_size=args.block_size , ref_path=_lowerCAmelCase , )
return LineByLineTextDataset(tokenizer=_lowerCAmelCase , file_path=_lowerCAmelCase , block_size=args.block_size )
else:
return TextDataset(
tokenizer=_lowerCAmelCase , file_path=_lowerCAmelCase , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=_lowerCAmelCase , )
if evaluate:
return _dataset(args.eval_data_file , args.eval_ref_file )
elif args.train_data_files:
return ConcatDataset([_dataset(_lowerCAmelCase ) for f in glob(args.train_data_files )] )
else:
return _dataset(args.train_data_file , args.train_ref_file )
def __snake_case( ) -> Dict:
# 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.
snake_case__ : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
snake_case__ , snake_case__ , snake_case__ : int = parser.parse_args_into_dataclasses()
if data_args.eval_data_file is None and training_args.do_eval:
raise ValueError(
"""Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """
"""or remove the --do_eval argument.""" )
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""" , _lowerCAmelCase )
# Set seed
set_seed(training_args.seed )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if model_args.config_name:
snake_case__ : Any = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
snake_case__ : Any = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir )
else:
snake_case__ : Tuple = CONFIG_MAPPING[model_args.model_type]()
logger.warning("""You are instantiating a new config instance from scratch.""" )
if model_args.tokenizer_name:
snake_case__ : str = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
snake_case__ : str = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir )
else:
raise ValueError(
"""You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another"""
""" script, save it,and load it from here, using --tokenizer_name""" )
if model_args.model_name_or_path:
snake_case__ : Union[str, Any] = AutoModelWithLMHead.from_pretrained(
model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=_lowerCAmelCase , cache_dir=model_args.cache_dir , )
else:
logger.info("""Training new model from scratch""" )
snake_case__ : List[Any] = AutoModelWithLMHead.from_config(_lowerCAmelCase )
model.resize_token_embeddings(len(_lowerCAmelCase ) )
if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
raise ValueError(
"""BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the"""
"""--mlm flag (masked language modeling).""" )
if data_args.block_size <= 0:
snake_case__ : List[Any] = tokenizer.max_len
# Our input block size will be the max possible for the model
else:
snake_case__ : List[str] = min(data_args.block_size , tokenizer.max_len )
# Get datasets
snake_case__ : int = (
get_dataset(_lowerCAmelCase , tokenizer=_lowerCAmelCase , cache_dir=model_args.cache_dir ) if training_args.do_train else None
)
snake_case__ : Any = (
get_dataset(_lowerCAmelCase , tokenizer=_lowerCAmelCase , evaluate=_lowerCAmelCase , cache_dir=model_args.cache_dir )
if training_args.do_eval
else None
)
if config.model_type == "xlnet":
snake_case__ : str = DataCollatorForPermutationLanguageModeling(
tokenizer=_lowerCAmelCase , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , )
else:
if data_args.mlm and data_args.whole_word_mask:
snake_case__ : List[str] = DataCollatorForWholeWordMask(
tokenizer=_lowerCAmelCase , mlm_probability=data_args.mlm_probability )
else:
snake_case__ : Optional[int] = DataCollatorForLanguageModeling(
tokenizer=_lowerCAmelCase , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability )
# Initialize our Trainer
snake_case__ : Optional[Any] = Trainer(
model=_lowerCAmelCase , args=_lowerCAmelCase , data_collator=_lowerCAmelCase , train_dataset=_lowerCAmelCase , eval_dataset=_lowerCAmelCase , prediction_loss_only=_lowerCAmelCase , )
# Training
if training_args.do_train:
snake_case__ : Any = (
model_args.model_name_or_path
if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path )
else None
)
trainer.train(model_path=_lowerCAmelCase )
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
snake_case__ : Union[str, Any] = {}
if training_args.do_eval:
logger.info("""*** Evaluate ***""" )
snake_case__ : Dict = trainer.evaluate()
snake_case__ : Dict = math.exp(eval_output["""eval_loss"""] )
snake_case__ : str = {"""perplexity""": perplexity}
snake_case__ : Any = os.path.join(training_args.output_dir , """eval_results_lm.txt""" )
if trainer.is_world_master():
with open(_lowerCAmelCase , """w""" ) as writer:
logger.info("""***** Eval results *****""" )
for key in sorted(result.keys() ):
logger.info(""" %s = %s""" , _lowerCAmelCase , str(result[key] ) )
writer.write("""%s = %s\n""" % (key, str(result[key] )) )
results.update(_lowerCAmelCase )
return results
def __snake_case( _lowerCAmelCase ) -> Tuple:
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| 374 | 0 |
'''simple docstring'''
import os
def _UpperCamelCase ( ) -> Dict:
lowerCamelCase_ = os.path.join(os.path.dirname(__UpperCamelCase ) ,'num.txt' )
with open(__UpperCamelCase ) as file_hand:
return str(sum(int(__UpperCamelCase ) for line in file_hand ) )[:10]
if __name__ == "__main__":
print(solution())
| 384 |
'''simple docstring'''
import unittest
from transformers.testing_utils import require_bsa
from transformers.utils import is_bsa_available
from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin
if is_bsa_available():
from transformers import MarkupLMFeatureExtractor
class UpperCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = parent
def UpperCamelCase( self ) -> Optional[int]:
'''simple docstring'''
return {}
def _UpperCamelCase ( ) -> Any:
lowerCamelCase_ = '<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR="FFFFFF">\n <HR>\n <a href="http://google.com">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style="color:#0000FF">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>'
lowerCamelCase_ = '\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n '
return [html_string_a, html_string_a]
@require_bsa
class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = MarkupLMFeatureExtractor if is_bsa_available() else None
def UpperCamelCase( self ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase_ = MarkupLMFeatureExtractionTester(self )
@property
def UpperCamelCase( self ) -> Optional[Any]:
'''simple docstring'''
return self.feature_extract_tester.prepare_feat_extract_dict()
def UpperCamelCase( self ) -> Any:
'''simple docstring'''
lowerCamelCase_ = self.feature_extraction_class()
# Test not batched input
lowerCamelCase_ = get_html_strings()[0]
lowerCamelCase_ = feature_extractor(SCREAMING_SNAKE_CASE_ )
# fmt: off
lowerCamelCase_ = [['sample document', 'Goog', 'This is one header', 'This is a another Header', 'Travel from', 'SFO to JFK', 'on May 2, 2015 at 2:00 pm. For details go to confirm.com', 'Traveler', 'name', 'is', 'John Doe']]
lowerCamelCase_ = [['/html/head/title', '/html/body/a', '/html/body/h1', '/html/body/h2', '/html/body/p', '/html/body/p/p/b[1]', '/html/body/p/p/b[2]/i', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/b', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/p']]
# fmt: on
self.assertEqual(encoding.nodes , SCREAMING_SNAKE_CASE_ )
self.assertEqual(encoding.xpaths , SCREAMING_SNAKE_CASE_ )
# Test batched
lowerCamelCase_ = get_html_strings()
lowerCamelCase_ = feature_extractor(SCREAMING_SNAKE_CASE_ )
# fmt: off
lowerCamelCase_ = expected_nodes + [['My First Heading', 'My first paragraph.']]
lowerCamelCase_ = expected_xpaths + [['/html/body/h1', '/html/body/p']]
self.assertEqual(len(encoding.nodes ) , 2 )
self.assertEqual(len(encoding.xpaths ) , 2 )
self.assertEqual(encoding.nodes , SCREAMING_SNAKE_CASE_ )
self.assertEqual(encoding.xpaths , SCREAMING_SNAKE_CASE_ )
| 384 | 1 |
import unittest
import numpy as np
from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
expand_dims,
flatten_dict,
is_flax_available,
is_tf_available,
is_torch_available,
reshape,
squeeze,
transpose,
)
if is_flax_available():
import jax.numpy as jnp
if is_tf_available():
import tensorflow as tf
if is_torch_available():
import torch
class lowercase ( unittest.TestCase ):
"""simple docstring"""
def _UpperCamelCase ( self : Union[str, Any] ):
"""simple docstring"""
lowerCamelCase__ = {
"""task_specific_params""": {
"""summarization""": {"""length_penalty""": 1.0, """max_length""": 1_28, """min_length""": 12, """num_beams""": 4},
"""summarization_cnn""": {"""length_penalty""": 2.0, """max_length""": 1_42, """min_length""": 56, """num_beams""": 4},
"""summarization_xsum""": {"""length_penalty""": 1.0, """max_length""": 62, """min_length""": 11, """num_beams""": 6},
}
}
lowerCamelCase__ = {
"""task_specific_params.summarization.length_penalty""": 1.0,
"""task_specific_params.summarization.max_length""": 1_28,
"""task_specific_params.summarization.min_length""": 12,
"""task_specific_params.summarization.num_beams""": 4,
"""task_specific_params.summarization_cnn.length_penalty""": 2.0,
"""task_specific_params.summarization_cnn.max_length""": 1_42,
"""task_specific_params.summarization_cnn.min_length""": 56,
"""task_specific_params.summarization_cnn.num_beams""": 4,
"""task_specific_params.summarization_xsum.length_penalty""": 1.0,
"""task_specific_params.summarization_xsum.max_length""": 62,
"""task_specific_params.summarization_xsum.min_length""": 11,
"""task_specific_params.summarization_xsum.num_beams""": 6,
}
self.assertEqual(flatten_dict(_lowerCAmelCase ) , _lowerCAmelCase )
def _UpperCamelCase ( self : str ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase ) , x.transpose() ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) )
@require_torch
def _UpperCamelCase ( self : str ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = torch.tensor(_lowerCAmelCase )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase ) , transpose(_lowerCAmelCase ).numpy() ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
lowerCamelCase__ = torch.tensor(_lowerCAmelCase )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase , axes=(1, 2, 0) ) , transpose(_lowerCAmelCase , axes=(1, 2, 0) ).numpy() ) )
@require_tf
def _UpperCamelCase ( self : Tuple ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = tf.constant(_lowerCAmelCase )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase ) , transpose(_lowerCAmelCase ).numpy() ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
lowerCamelCase__ = tf.constant(_lowerCAmelCase )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase , axes=(1, 2, 0) ) , transpose(_lowerCAmelCase , axes=(1, 2, 0) ).numpy() ) )
@require_flax
def _UpperCamelCase ( self : str ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = jnp.array(_lowerCAmelCase )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase ) , np.asarray(transpose(_lowerCAmelCase ) ) ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
lowerCamelCase__ = jnp.array(_lowerCAmelCase )
self.assertTrue(np.allclose(transpose(_lowerCAmelCase , axes=(1, 2, 0) ) , np.asarray(transpose(_lowerCAmelCase , axes=(1, 2, 0) ) ) ) )
def _UpperCamelCase ( self : List[Any] ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (4, 3) ) , np.reshape(_lowerCAmelCase , (4, 3) ) ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (12, 5) ) , np.reshape(_lowerCAmelCase , (12, 5) ) ) )
@require_torch
def _UpperCamelCase ( self : Any ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = torch.tensor(_lowerCAmelCase )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (4, 3) ) , reshape(_lowerCAmelCase , (4, 3) ).numpy() ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
lowerCamelCase__ = torch.tensor(_lowerCAmelCase )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (12, 5) ) , reshape(_lowerCAmelCase , (12, 5) ).numpy() ) )
@require_tf
def _UpperCamelCase ( self : List[Any] ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = tf.constant(_lowerCAmelCase )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (4, 3) ) , reshape(_lowerCAmelCase , (4, 3) ).numpy() ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
lowerCamelCase__ = tf.constant(_lowerCAmelCase )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (12, 5) ) , reshape(_lowerCAmelCase , (12, 5) ).numpy() ) )
@require_flax
def _UpperCamelCase ( self : List[str] ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = jnp.array(_lowerCAmelCase )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (4, 3) ) , np.asarray(reshape(_lowerCAmelCase , (4, 3) ) ) ) )
lowerCamelCase__ = np.random.randn(3 , 4 , 5 )
lowerCamelCase__ = jnp.array(_lowerCAmelCase )
self.assertTrue(np.allclose(reshape(_lowerCAmelCase , (12, 5) ) , np.asarray(reshape(_lowerCAmelCase , (12, 5) ) ) ) )
def _UpperCamelCase ( self : Dict ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(1 , 3 , 4 )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase ) , np.squeeze(_lowerCAmelCase ) ) )
lowerCamelCase__ = np.random.randn(1 , 4 , 1 , 5 )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase , axis=2 ) , np.squeeze(_lowerCAmelCase , axis=2 ) ) )
@require_torch
def _UpperCamelCase ( self : List[Any] ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(1 , 3 , 4 )
lowerCamelCase__ = torch.tensor(_lowerCAmelCase )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase ) , squeeze(_lowerCAmelCase ).numpy() ) )
lowerCamelCase__ = np.random.randn(1 , 4 , 1 , 5 )
lowerCamelCase__ = torch.tensor(_lowerCAmelCase )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase , axis=2 ) , squeeze(_lowerCAmelCase , axis=2 ).numpy() ) )
@require_tf
def _UpperCamelCase ( self : str ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(1 , 3 , 4 )
lowerCamelCase__ = tf.constant(_lowerCAmelCase )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase ) , squeeze(_lowerCAmelCase ).numpy() ) )
lowerCamelCase__ = np.random.randn(1 , 4 , 1 , 5 )
lowerCamelCase__ = tf.constant(_lowerCAmelCase )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase , axis=2 ) , squeeze(_lowerCAmelCase , axis=2 ).numpy() ) )
@require_flax
def _UpperCamelCase ( self : Tuple ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(1 , 3 , 4 )
lowerCamelCase__ = jnp.array(_lowerCAmelCase )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase ) , np.asarray(squeeze(_lowerCAmelCase ) ) ) )
lowerCamelCase__ = np.random.randn(1 , 4 , 1 , 5 )
lowerCamelCase__ = jnp.array(_lowerCAmelCase )
self.assertTrue(np.allclose(squeeze(_lowerCAmelCase , axis=2 ) , np.asarray(squeeze(_lowerCAmelCase , axis=2 ) ) ) )
def _UpperCamelCase ( self : Optional[int] ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
self.assertTrue(np.allclose(expand_dims(_lowerCAmelCase , axis=1 ) , np.expand_dims(_lowerCAmelCase , axis=1 ) ) )
@require_torch
def _UpperCamelCase ( self : Any ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = torch.tensor(_lowerCAmelCase )
self.assertTrue(np.allclose(expand_dims(_lowerCAmelCase , axis=1 ) , expand_dims(_lowerCAmelCase , axis=1 ).numpy() ) )
@require_tf
def _UpperCamelCase ( self : Optional[Any] ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = tf.constant(_lowerCAmelCase )
self.assertTrue(np.allclose(expand_dims(_lowerCAmelCase , axis=1 ) , expand_dims(_lowerCAmelCase , axis=1 ).numpy() ) )
@require_flax
def _UpperCamelCase ( self : Optional[int] ):
"""simple docstring"""
lowerCamelCase__ = np.random.randn(3 , 4 )
lowerCamelCase__ = jnp.array(_lowerCAmelCase )
self.assertTrue(np.allclose(expand_dims(_lowerCAmelCase , axis=1 ) , np.asarray(expand_dims(_lowerCAmelCase , axis=1 ) ) ) )
| 165 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowercase_ : str = {'''configuration_sew''': ['''SEW_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SEWConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ : Optional[int] = [
'''SEW_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''SEWForCTC''',
'''SEWForSequenceClassification''',
'''SEWModel''',
'''SEWPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_sew import (
SEW_PRETRAINED_MODEL_ARCHIVE_LIST,
SEWForCTC,
SEWForSequenceClassification,
SEWModel,
SEWPreTrainedModel,
)
else:
import sys
lowercase_ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 588 | 0 |
from collections.abc import Callable
import numpy as np
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase):
UpperCamelCase_ = int(np.ceil((x_end - xa) / step_size))
UpperCamelCase_ = np.zeros((n + 1,))
UpperCamelCase_ = ya
UpperCamelCase_ = xa
for k in range(_lowerCAmelCase):
UpperCamelCase_ = y[k] + step_size * ode_func(_lowerCAmelCase , y[k])
UpperCamelCase_ = y[k] + (
(step_size / 2) * (ode_func(_lowerCAmelCase , y[k]) + ode_func(x + step_size , _lowerCAmelCase))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 504 |
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
UpperCAmelCase : Optional[Any] =pytest.mark.integration
@pytest.mark.parametrize("path" , ["paws", "csv"])
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase):
inspect_dataset(_lowerCAmelCase , _lowerCAmelCase)
UpperCamelCase_ = path + ".py"
assert script_name in os.listdir(_lowerCAmelCase)
assert "__pycache__" not in os.listdir(_lowerCAmelCase)
@pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning")
@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning")
@pytest.mark.parametrize("path" , ["accuracy"])
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase):
inspect_metric(_lowerCAmelCase , _lowerCAmelCase)
UpperCamelCase_ = path + ".py"
assert script_name in os.listdir(_lowerCAmelCase)
assert "__pycache__" not in os.listdir(_lowerCAmelCase)
@pytest.mark.parametrize(
"path, config_name, expected_splits" , [
("squad", "plain_text", ["train", "validation"]),
("dalle-mini/wit", "dalle-mini--wit", ["train"]),
("paws", "labeled_final", ["train", "test", "validation"]),
] , )
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase):
UpperCamelCase_ = get_dataset_config_info(_lowerCAmelCase , config_name=_lowerCAmelCase)
assert info.config_name == config_name
assert list(info.splits.keys()) == expected_splits
@pytest.mark.parametrize(
"path, config_name, expected_exception" , [
("paws", None, ValueError),
] , )
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase):
with pytest.raises(_lowerCAmelCase):
get_dataset_config_info(_lowerCAmelCase , config_name=_lowerCAmelCase)
@pytest.mark.parametrize(
"path, expected" , [
("squad", "plain_text"),
("acronym_identification", "default"),
("lhoestq/squad", "plain_text"),
("lhoestq/test", "default"),
("lhoestq/demo1", "lhoestq--demo1"),
("dalle-mini/wit", "dalle-mini--wit"),
] , )
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase):
UpperCamelCase_ = get_dataset_config_names(_lowerCAmelCase)
assert expected in config_names
@pytest.mark.parametrize(
"path, expected_configs, expected_splits_in_first_config" , [
("squad", ["plain_text"], ["train", "validation"]),
("dalle-mini/wit", ["dalle-mini--wit"], ["train"]),
("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]),
] , )
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase):
UpperCamelCase_ = get_dataset_infos(_lowerCAmelCase)
assert list(infos.keys()) == expected_configs
UpperCamelCase_ = expected_configs[0]
assert expected_config in infos
UpperCamelCase_ = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys()) == expected_splits_in_first_config
@pytest.mark.parametrize(
"path, expected_config, expected_splits" , [
("squad", "plain_text", ["train", "validation"]),
("dalle-mini/wit", "dalle-mini--wit", ["train"]),
("paws", "labeled_final", ["train", "test", "validation"]),
] , )
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase):
UpperCamelCase_ = get_dataset_infos(_lowerCAmelCase)
assert expected_config in infos
UpperCamelCase_ = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys()) == expected_splits
@pytest.mark.parametrize(
"path, config_name, expected_exception" , [
("paws", None, ValueError),
] , )
def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase):
with pytest.raises(_lowerCAmelCase):
get_dataset_split_names(_lowerCAmelCase , config_name=_lowerCAmelCase)
| 504 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.