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 gc
import random
import tempfile
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu
class _UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
def __UpperCamelCase ( self : Union[str, Any] ) -> int:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def __UpperCamelCase ( self : Tuple ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = 1
SCREAMING_SNAKE_CASE : str = 3
SCREAMING_SNAKE_CASE : int = (32, 32)
SCREAMING_SNAKE_CASE : str = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(a )
return image
@property
def __UpperCamelCase ( self : Optional[Any] ) -> str:
"""simple docstring"""
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Dict = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , )
return model
@property
def __UpperCamelCase ( self : int ) -> Any:
"""simple docstring"""
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : 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 , )
return model
@property
def __UpperCamelCase ( self : Tuple ) -> str:
"""simple docstring"""
torch.manual_seed(0 )
SCREAMING_SNAKE_CASE : Tuple = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )
return CLIPTextModel(a )
@property
def __UpperCamelCase ( self : List[str] ) -> str:
"""simple docstring"""
def extract(*a : int , **a : Union[str, Any] ):
class _UpperCamelCase :
'''simple docstring'''
def __init__( self : Optional[Any] ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = torch.ones([0] )
def __UpperCamelCase ( self : str , a : List[Any] ) -> List[str]:
"""simple docstring"""
self.pixel_values.to(a )
return self
return Out()
return extract
def __UpperCamelCase ( self : List[Any] ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator
SCREAMING_SNAKE_CASE : int = self.dummy_cond_unet
SCREAMING_SNAKE_CASE : Dict = DDIMScheduler(
beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=a , set_alpha_to_one=a , )
SCREAMING_SNAKE_CASE : Tuple = self.dummy_vae
SCREAMING_SNAKE_CASE : Dict = self.dummy_text_encoder
SCREAMING_SNAKE_CASE : Dict = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
# make sure here that pndm scheduler skips prk
SCREAMING_SNAKE_CASE : int = StableDiffusionPipeline(
unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , )
SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(a )
sd_pipe.set_progress_bar_config(disable=a )
SCREAMING_SNAKE_CASE : Union[str, Any] = "A painting of a squirrel eating a burger"
SCREAMING_SNAKE_CASE : Any = torch.Generator(device=a ).manual_seed(0 )
SCREAMING_SNAKE_CASE : Dict = sd_pipe([prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" )
SCREAMING_SNAKE_CASE : Dict = output.images
SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=a ).manual_seed(0 )
SCREAMING_SNAKE_CASE : Any = sd_pipe(
[prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a , )[0]
SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : Dict = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
SCREAMING_SNAKE_CASE : Tuple = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
def __UpperCamelCase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator
SCREAMING_SNAKE_CASE : List[str] = self.dummy_cond_unet
SCREAMING_SNAKE_CASE : Tuple = PNDMScheduler(skip_prk_steps=a )
SCREAMING_SNAKE_CASE : Dict = self.dummy_vae
SCREAMING_SNAKE_CASE : Dict = self.dummy_text_encoder
SCREAMING_SNAKE_CASE : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
# make sure here that pndm scheduler skips prk
SCREAMING_SNAKE_CASE : List[str] = StableDiffusionPipeline(
unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , )
SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe.to(a )
sd_pipe.set_progress_bar_config(disable=a )
SCREAMING_SNAKE_CASE : List[str] = "A painting of a squirrel eating a burger"
SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device=a ).manual_seed(0 )
SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe([prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" )
SCREAMING_SNAKE_CASE : int = output.images
SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device=a ).manual_seed(0 )
SCREAMING_SNAKE_CASE : List[str] = sd_pipe(
[prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a , )[0]
SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : str = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
SCREAMING_SNAKE_CASE : Any = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
def __UpperCamelCase ( self : Dict ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionPipeline.from_pretrained(
"hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=a )
assert isinstance(a , a )
assert isinstance(pipe.scheduler , a )
assert pipe.safety_checker is None
SCREAMING_SNAKE_CASE : Tuple = pipe("example prompt" , num_inference_steps=2 ).images[0]
assert image is not None
# check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(a )
SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionPipeline.from_pretrained(a )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
SCREAMING_SNAKE_CASE : Dict = pipe("example prompt" , num_inference_steps=2 ).images[0]
assert image is not None
@unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" )
def __UpperCamelCase ( self : Dict ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = self.dummy_cond_unet
SCREAMING_SNAKE_CASE : Dict = PNDMScheduler(skip_prk_steps=a )
SCREAMING_SNAKE_CASE : Dict = self.dummy_vae
SCREAMING_SNAKE_CASE : Dict = self.dummy_text_encoder
SCREAMING_SNAKE_CASE : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )
# put models in fp16
SCREAMING_SNAKE_CASE : Tuple = unet.half()
SCREAMING_SNAKE_CASE : Tuple = vae.half()
SCREAMING_SNAKE_CASE : Tuple = bert.half()
# make sure here that pndm scheduler skips prk
SCREAMING_SNAKE_CASE : str = StableDiffusionPipeline(
unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , )
SCREAMING_SNAKE_CASE : List[Any] = sd_pipe.to(a )
sd_pipe.set_progress_bar_config(disable=a )
SCREAMING_SNAKE_CASE : List[Any] = "A painting of a squirrel eating a burger"
SCREAMING_SNAKE_CASE : Tuple = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images
assert image.shape == (1, 64, 64, 3)
@nightly
@require_torch_gpu
class _UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
def __UpperCamelCase ( self : Tuple ) -> Optional[int]:
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __UpperCamelCase ( self : Any ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a )
SCREAMING_SNAKE_CASE : Tuple = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe.to(a )
sd_pipe.set_progress_bar_config(disable=a )
SCREAMING_SNAKE_CASE : Optional[int] = (
"portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle"
" coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with"
" anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and"
" children from bahnhof zoo, detailed "
)
SCREAMING_SNAKE_CASE : Union[str, Any] = 40_0366_0346
SCREAMING_SNAKE_CASE : Tuple = 7
# without safety guidance (sld_guidance_scale = 0)
SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(a )
SCREAMING_SNAKE_CASE : Dict = sd_pipe(
[prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , )
SCREAMING_SNAKE_CASE : Union[str, Any] = output.images
SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : List[str] = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
# without safety guidance (strong configuration)
SCREAMING_SNAKE_CASE : Optional[int] = torch.manual_seed(a )
SCREAMING_SNAKE_CASE : str = sd_pipe(
[prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , )
SCREAMING_SNAKE_CASE : Union[str, Any] = output.images
SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : List[Any] = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def __UpperCamelCase ( self : str ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a )
SCREAMING_SNAKE_CASE : Union[str, Any] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
SCREAMING_SNAKE_CASE : Any = sd_pipe.to(a )
sd_pipe.set_progress_bar_config(disable=a )
SCREAMING_SNAKE_CASE : Union[str, Any] = "padme amidala taking a bath artwork, safe for work, no nudity"
SCREAMING_SNAKE_CASE : Optional[int] = 27_3497_1755
SCREAMING_SNAKE_CASE : Optional[Any] = 7
SCREAMING_SNAKE_CASE : str = torch.manual_seed(a )
SCREAMING_SNAKE_CASE : Dict = sd_pipe(
[prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , )
SCREAMING_SNAKE_CASE : List[Any] = output.images
SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : Any = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
SCREAMING_SNAKE_CASE : int = torch.manual_seed(a )
SCREAMING_SNAKE_CASE : List[str] = sd_pipe(
[prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , )
SCREAMING_SNAKE_CASE : Dict = output.images
SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : Optional[Any] = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def __UpperCamelCase ( self : Tuple ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" )
SCREAMING_SNAKE_CASE : List[str] = sd_pipe.to(a )
sd_pipe.set_progress_bar_config(disable=a )
SCREAMING_SNAKE_CASE : Optional[Any] = (
"the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c."
" leyendecker"
)
SCREAMING_SNAKE_CASE : str = 10_4435_5234
SCREAMING_SNAKE_CASE : List[str] = 12
SCREAMING_SNAKE_CASE : Any = torch.manual_seed(a )
SCREAMING_SNAKE_CASE : Optional[int] = sd_pipe(
[prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , )
SCREAMING_SNAKE_CASE : Tuple = output.images
SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : List[Any] = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] )
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7
SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(a )
SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe(
[prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , )
SCREAMING_SNAKE_CASE : Dict = output.images
SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1]
SCREAMING_SNAKE_CASE : Tuple = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] )
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 | 25 |
'''simple docstring'''
# Function to print upper half of diamond (pyramid)
def __UpperCamelCase ( lowercase__ : Optional[Any] ):
'''simple docstring'''
for i in range(0, lowercase__ ):
for _ in range(0, n - i - 1 ): # printing spaces
print(' ', end='' )
for _ in range(0, i + 1 ): # printing stars
print('* ', end='' )
print()
def __UpperCamelCase ( lowercase__ : Optional[Any] ):
'''simple docstring'''
for i in range(lowercase__, 0, -1 ):
for _ in range(lowercase__, 0, -1 ): # printing stars
print('* ', end='' )
print()
for _ in range(n - i + 1, 0, -1 ): # printing spaces
print(' ', end='' )
def __UpperCamelCase ( lowercase__ : Any ):
'''simple docstring'''
if n <= 0:
print(' ... .... nothing printing :(' )
return
floyd(lowercase__ ) # upper half
reverse_floyd(lowercase__ ) # lower half
if __name__ == "__main__":
print(r'''| /\ | |- | |- |--| |\ /| |-''')
print(r'''|/ \| |- |_ |_ |__| | \/ | |_''')
UpperCAmelCase = 1
while K:
UpperCAmelCase = int(input('''enter the number and , and see the magic : '''))
print()
pretty_print(user_number)
UpperCAmelCase = int(input('''press 0 to exit... and 1 to continue...'''))
print('''Good Bye...''')
| 119 | 0 |
from __future__ import annotations
import string
from itertools import cycle, product
from pathlib import Path
__UpperCAmelCase : str = (
string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
__UpperCAmelCase : list[int] = [ord(letter) for letter in string.ascii_lowercase]
__UpperCAmelCase : set[int] = {ord(char) for char in VALID_CHARS}
__UpperCAmelCase : list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"]
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> str | None:
__snake_case: str = ""
__snake_case: int
__snake_case: int
__snake_case: int
for keychar, cipherchar in zip(cycle(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE__):
__snake_case: Any = cipherchar ^ keychar
if decodedchar not in VALID_INTS:
return None
decoded += chr(SCREAMING_SNAKE_CASE__)
return decoded
def A__ ( SCREAMING_SNAKE_CASE__) -> list[str]:
__snake_case: list[str] = []
for key in product(SCREAMING_SNAKE_CASE__ , repeat=3):
__snake_case: List[Any] = try_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)
if encoded is not None:
possibles.append(SCREAMING_SNAKE_CASE__)
return possibles
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> list[str]:
return [possible for possible in possibles if common_word in possible.lower()]
def A__ ( SCREAMING_SNAKE_CASE__ = "p059_cipher.txt") -> int:
__snake_case: list[int]
__snake_case: list[str]
__snake_case: str
__snake_case: str
__snake_case: str = Path(SCREAMING_SNAKE_CASE__).parent.joinpath(SCREAMING_SNAKE_CASE__).read_text(encoding="""utf-8""")
__snake_case: Optional[int] = [int(SCREAMING_SNAKE_CASE__) for number in data.strip().split(""",""")]
__snake_case: int = filter_valid_chars(SCREAMING_SNAKE_CASE__)
for common_word in COMMON_WORDS:
__snake_case: List[Any] = filter_common_word(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)
if len(SCREAMING_SNAKE_CASE__) == 1:
break
__snake_case: Tuple = possibles[0]
return sum(ord(SCREAMING_SNAKE_CASE__) for char in decoded_text)
if __name__ == "__main__":
print(f'{solution() = }')
| 708 |
import json
import sys
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> Optional[int]:
with open(SCREAMING_SNAKE_CASE__ , encoding="""utf-8""") as f:
__snake_case: Tuple = json.load(SCREAMING_SNAKE_CASE__)
__snake_case: Union[str, Any] = ["""<details>""", """<summary>Show updated benchmarks!</summary>""", """ """]
for benchmark_name in sorted(SCREAMING_SNAKE_CASE__):
__snake_case: str = results[benchmark_name]
__snake_case: List[Any] = benchmark_name.split("""/""")[-1]
output_md.append(F'''### Benchmark: {benchmark_file_name}''')
__snake_case: Optional[Any] = """| metric |"""
__snake_case: Optional[Any] = """|--------|"""
__snake_case: Dict = """| new / old (diff) |"""
for metric_name in sorted(SCREAMING_SNAKE_CASE__):
__snake_case: Tuple = benchmark_res[metric_name]
__snake_case: int = metric_vals["""new"""]
__snake_case: List[str] = metric_vals.get("""old""" , SCREAMING_SNAKE_CASE__)
__snake_case: Optional[Any] = metric_vals.get("""diff""" , SCREAMING_SNAKE_CASE__)
__snake_case: Optional[int] = F''' {new_val:f}''' if isinstance(SCREAMING_SNAKE_CASE__ , (int, float)) else """None"""
if old_val is not None:
val_str += F''' / {old_val:f}''' if isinstance(SCREAMING_SNAKE_CASE__ , (int, float)) else "None"
if dif_val is not None:
val_str += F''' ({dif_val:f})''' if isinstance(SCREAMING_SNAKE_CASE__ , (int, float)) else "None"
title += " " + metric_name + " |"
lines += "---|"
value += val_str + " |"
output_md += [title, lines, value, " "]
output_md.append("""</details>""")
with open(SCREAMING_SNAKE_CASE__ , """w""" , encoding="""utf-8""") as f:
f.writelines("""\n""".join(SCREAMING_SNAKE_CASE__))
if __name__ == "__main__":
__UpperCAmelCase : List[Any] = sys.argv[1]
__UpperCAmelCase : Any = sys.argv[2]
format_json_to_md(input_json_file, output_md_file)
| 155 | 0 |
'''simple docstring'''
import pytest
_UpperCamelCase = """__dummy_dataset1__"""
_UpperCamelCase = """
import json
import os
import datasets
REPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\"
URLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \"validation\": REPO_URL + \"wikiann-bn-validation.jsonl\"}
class __DummyDataset1__(datasets.GeneratorBasedBuilder):
def _info(self):
features = datasets.Features(
{
\"tokens\": datasets.Sequence(datasets.Value(\"string\")),
\"ner_tags\": datasets.Sequence(
datasets.features.ClassLabel(
names=[
\"O\",
\"B-PER\",
\"I-PER\",
\"B-ORG\",
\"I-ORG\",
\"B-LOC\",
\"I-LOC\",
]
)
),
\"langs\": datasets.Sequence(datasets.Value(\"string\")),
\"spans\": datasets.Sequence(datasets.Value(\"string\")),
}
)
return datasets.DatasetInfo(features=features)
def _split_generators(self, dl_manager):
dl_path = dl_manager.download(URLS)
return [
datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={\"filepath\": dl_path[\"train\"]}),
datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={\"filepath\": dl_path[\"validation\"]}),
]
def _generate_examples(self, filepath):
with open(filepath, \"r\", encoding=\"utf-8\") as f:
for i, line in enumerate(f):
yield i, json.loads(line)
"""
@pytest.fixture
def _lowercase ():
'''simple docstring'''
return DATASET_LOADING_SCRIPT_NAME
@pytest.fixture
def _lowercase ():
'''simple docstring'''
return DATASET_LOADING_SCRIPT_CODE
@pytest.fixture
def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
__A : int = dataset_loading_script_name
__A : Optional[Any] = tmp_path / "datasets" / script_name
script_dir.mkdir(parents=SCREAMING_SNAKE_CASE )
__A : str = script_dir / f"{script_name}.py"
with open(SCREAMING_SNAKE_CASE , "w" ) as f:
f.write(SCREAMING_SNAKE_CASE )
return str(SCREAMING_SNAKE_CASE )
| 111 |
'''simple docstring'''
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
_UpperCamelCase = logging.get_logger(__name__)
def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
__A : int = b.T
__A : Optional[Any] = np.sum(np.square(SCREAMING_SNAKE_CASE ) , axis=1 )
__A : List[Any] = np.sum(np.square(SCREAMING_SNAKE_CASE ) , axis=0 )
__A : List[Any] = np.matmul(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
__A : str = aa[:, None] - 2 * ab + ba[None, :]
return d
def _lowercase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
__A : Union[str, Any] = x.reshape(-1 , 3 )
__A : Any = squared_euclidean_distance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
return np.argmin(SCREAMING_SNAKE_CASE , axis=1 )
class __magic_name__ ( lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase__ = ['pixel_values']
def __init__( self , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BILINEAR , lowerCamelCase = True , lowerCamelCase = True , **lowerCamelCase , ):
'''simple docstring'''
super().__init__(**lowerCamelCase )
__A : Optional[int] = size if size is not None else {"height": 256, "width": 256}
__A : int = get_size_dict(lowerCamelCase )
__A : str = np.array(lowerCamelCase ) if clusters is not None else None
__A : List[Any] = do_resize
__A : Dict = size
__A : str = resample
__A : Optional[Any] = do_normalize
__A : Dict = do_color_quantize
def lowerCAmelCase__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BILINEAR , lowerCamelCase = None , **lowerCamelCase , ):
'''simple docstring'''
__A : Optional[Any] = get_size_dict(lowerCamelCase )
if "height" not in size or "width" not in size:
raise ValueError(f"Size dictionary must contain both height and width keys. Got {size.keys()}" )
return resize(
lowerCamelCase , size=(size["height"], size["width"]) , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase )
def lowerCAmelCase__ ( self , lowerCamelCase , lowerCamelCase = None , ):
'''simple docstring'''
__A : List[str] = rescale(image=lowerCamelCase , scale=1 / 127.5 , data_format=lowerCamelCase )
__A : List[Any] = image - 1
return image
def lowerCAmelCase__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ):
'''simple docstring'''
__A : List[Any] = do_resize if do_resize is not None else self.do_resize
__A : int = size if size is not None else self.size
__A : Tuple = get_size_dict(lowerCamelCase )
__A : Tuple = resample if resample is not None else self.resample
__A : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize
__A : Tuple = do_color_quantize if do_color_quantize is not None else self.do_color_quantize
__A : Any = clusters if clusters is not None else self.clusters
__A : Dict = np.array(lowerCamelCase )
__A : Optional[int] = 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_color_quantize and clusters is None:
raise ValueError("Clusters must be specified if do_color_quantize is True." )
# All transformations expect numpy arrays.
__A : Optional[Any] = [to_numpy_array(lowerCamelCase ) for image in images]
if do_resize:
__A : Dict = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images]
if do_normalize:
__A : List[Any] = [self.normalize(image=lowerCamelCase ) for image in images]
if do_color_quantize:
__A : Union[str, Any] = [to_channel_dimension_format(lowerCamelCase , ChannelDimension.LAST ) for image in images]
# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
__A : int = np.array(lowerCamelCase )
__A : Any = color_quantize(lowerCamelCase , lowerCamelCase ).reshape(images.shape[:-1] )
# flatten to (batch_size, height*width)
__A : Tuple = images.shape[0]
__A : List[Any] = images.reshape(lowerCamelCase , -1 )
# We need to convert back to a list of images to keep consistent behaviour across processors.
__A : Optional[int] = list(lowerCamelCase )
else:
__A : Tuple = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images]
__A : Optional[int] = {"input_ids": images}
return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
| 111 | 1 |
"""simple docstring"""
import os
import time
import pytest
from datasets.utils.filelock import FileLock, Timeout
def __A ( a_ : Dict )-> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = FileLock(str(tmpdir / '''foo.lock''' ) )
SCREAMING_SNAKE_CASE : Tuple = FileLock(str(tmpdir / '''foo.lock''' ) )
SCREAMING_SNAKE_CASE : Dict = 0.01
with locka.acquire():
with pytest.raises(lowercase__ ):
SCREAMING_SNAKE_CASE : Union[str, Any] = time.time()
locka.acquire(lowercase__ )
assert time.time() - _start > timeout
def __A ( a_ : Union[str, Any] )-> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = '''a''' * 10_00 + '''.lock'''
SCREAMING_SNAKE_CASE : Optional[int] = FileLock(str(tmpdir / filename ) )
assert locka._lock_file.endswith('''.lock''' )
assert not locka._lock_file.endswith(lowercase__ )
assert len(os.path.basename(locka._lock_file ) ) <= 2_55
SCREAMING_SNAKE_CASE : Union[str, Any] = FileLock(tmpdir / filename )
with locka.acquire():
with pytest.raises(lowercase__ ):
locka.acquire(0 )
| 718 |
"""simple docstring"""
import math
class lowercase__:
'''simple docstring'''
def __init__( self :Union[str, Any] , lowerCamelCase_ :List[str]=0 ) -> List[Any]: # a graph with Node 0,1,...,N-1
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = n
SCREAMING_SNAKE_CASE : List[Any] = [
[math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ )
] # adjacency matrix for weight
SCREAMING_SNAKE_CASE : Any = [
[math.inf for j in range(0 , lowerCamelCase_ )] for i in range(0 , lowerCamelCase_ )
] # dp[i][j] stores minimum distance from i to j
def __lowerCAmelCase ( self :Dict , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Union[str, Any] ) -> Tuple:
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = w
def __lowerCAmelCase ( self :str ) -> Union[str, Any]:
'''simple docstring'''
for k in range(0 , self.n ):
for i in range(0 , self.n ):
for j in range(0 , self.n ):
SCREAMING_SNAKE_CASE : List[str] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] )
def __lowerCAmelCase ( self :int , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Optional[int] ) -> Optional[Any]:
'''simple docstring'''
return self.dp[u][v]
if __name__ == "__main__":
lowerCamelCase__ : Dict = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 10)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 10)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3)
| 18 | 0 |
import gc
import importlib.metadata
import tempfile
import unittest
from packaging import version
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForSeqaSeqLM,
AutoModelForSequenceClassification,
AutoTokenizer,
BitsAndBytesConfig,
pipeline,
)
from transformers.testing_utils import (
is_torch_available,
require_accelerate,
require_bitsandbytes,
require_torch,
require_torch_gpu,
require_torch_multi_gpu,
slow,
)
def UpperCamelCase_ ( __a ) -> Union[str, Any]:
if model.config.model_type == "gpt2":
return model.transformer.h[0].mlp.c_fc
return model.transformer.h[0].mlp.dense_ah_to_h
if is_torch_available():
import torch
import torch.nn as nn
class A__ ( nn.Module ):
"""simple docstring"""
def __init__( self : List[str] , lowerCamelCase__ : nn.Module , lowerCamelCase__ : int ):
super().__init__()
a__ : int = module
a__ : Any = nn.Sequential(
nn.Linear(module.in_features , lowerCamelCase__ , bias=lowerCamelCase__ ) , nn.Linear(lowerCamelCase__ , module.out_features , bias=lowerCamelCase__ ) , )
a__ : Tuple = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5
nn.init.normal_(self.adapter[0].weight , std=lowerCamelCase__ )
nn.init.zeros_(self.adapter[1].weight )
self.adapter.to(module.weight.device )
def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : Optional[int] , *lowerCamelCase__ : int , **lowerCamelCase__ : Dict ):
return self.module(lowerCamelCase__ , *lowerCamelCase__ , **lowerCamelCase__ ) + self.adapter(lowerCamelCase__ )
@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class A__ ( unittest.TestCase ):
"""simple docstring"""
_lowercase = 'bigscience/bloom-1b7'
# Constant values
_lowercase = 2.1_09_65_95_52_69_25_74
_lowercase = 'Hello my name is'
_lowercase = set()
EXPECTED_OUTPUTS.add('Hello my name is John and I am a professional photographer. I' )
EXPECTED_OUTPUTS.add('Hello my name is John.\nI am a friend of your father.\n' )
EXPECTED_OUTPUTS.add('Hello my name is John Doe, I am a student at the University' )
_lowercase = 1_0
def _UpperCamelCase( self : Dict ):
# Models and tokenizer
a__ : List[str] = AutoTokenizer.from_pretrained(self.model_name )
class A__ ( A__ ):
"""simple docstring"""
def _UpperCamelCase( self : Union[str, Any] ):
super().setUp()
# Models and tokenizer
a__ : List[Any] = AutoModelForCausalLM.from_pretrained(
self.model_name , torch_dtype=torch.floataa , device_map="auto" )
a__ : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
def _UpperCamelCase( self : List[Any] ):
del self.model_fpaa
del self.model_abit
gc.collect()
torch.cuda.empty_cache()
def _UpperCamelCase( self : List[Any] ):
a__ : str = self.model_abit.config
self.assertTrue(hasattr(lowerCamelCase__ , "quantization_config" ) )
a__ : Optional[Any] = config.to_dict()
a__ : int = config.to_diff_dict()
a__ : List[str] = config.to_json_string()
def _UpperCamelCase( self : int ):
from bitsandbytes.nn import Paramsabit
a__ : List[Any] = self.model_fpaa.get_memory_footprint()
a__ : str = self.model_abit.get_memory_footprint()
self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE )
a__ : Optional[Any] = get_some_linear_layer(self.model_abit )
self.assertTrue(linear.weight.__class__ == Paramsabit )
def _UpperCamelCase( self : Tuple ):
from transformers import TaPreTrainedModel
self.model_fpaa.get_memory_footprint()
self.model_abit.get_memory_footprint()
for name, module in self.model_abit.named_modules():
if isinstance(lowerCamelCase__ , torch.nn.Linear ):
if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules:
# 4-bit parameters are packed in uint8 variables
self.assertTrue(module.weight.dtype == torch.uinta )
def _UpperCamelCase( self : str ):
a__ : Dict = self.tokenizer(self.input_text , return_tensors="pt" )
a__ : Tuple = self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowerCamelCase__ ) , self.EXPECTED_OUTPUTS )
def _UpperCamelCase( self : List[Any] ):
a__ : Optional[Any] = BitsAndBytesConfig()
a__ : Optional[int] = True
a__ : int = AutoModelForCausalLM.from_pretrained(
self.model_name , quantization_config=lowerCamelCase__ , device_map="auto" )
a__ : str = self.tokenizer(self.input_text , return_tensors="pt" )
a__ : int = model_abit_from_config.generate(
input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowerCamelCase__ ) , self.EXPECTED_OUTPUTS )
def _UpperCamelCase( self : Dict ):
with self.assertRaises(lowerCamelCase__ ), tempfile.TemporaryDirectory() as tmpdirname:
self.model_abit.save_pretrained(lowerCamelCase__ )
def _UpperCamelCase( self : Union[str, Any] ):
a__ : int = BitsAndBytesConfig()
with self.assertRaises(lowerCamelCase__ ):
a__ : Dict = AutoModelForCausalLM.from_pretrained(
self.model_name , quantization_config=lowerCamelCase__ , load_in_abit=lowerCamelCase__ , device_map="auto" , bnb_abit_quant_type="nf4" , )
def _UpperCamelCase( self : int ):
with self.assertRaises(lowerCamelCase__ ):
# Tries with `str`
self.model_abit.to("cpu" )
with self.assertRaises(lowerCamelCase__ ):
# Tries with a `dtype``
self.model_abit.to(torch.floataa )
with self.assertRaises(lowerCamelCase__ ):
# Tries with a `device`
self.model_abit.to(torch.device("cuda:0" ) )
with self.assertRaises(lowerCamelCase__ ):
# Tries with a `device`
self.model_abit.float()
with self.assertRaises(lowerCamelCase__ ):
# Tries with a `device`
self.model_abit.half()
# Test if we did not break anything
a__ : int = self.tokenizer(self.input_text , return_tensors="pt" )
a__ : Any = self.model_fpaa.to(torch.floataa )
a__ : List[Any] = self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
# Check this does not throw an error
a__ : Tuple = self.model_fpaa.to("cpu" )
# Check this does not throw an error
a__ : Tuple = self.model_fpaa.half()
# Check this does not throw an error
a__ : Dict = self.model_fpaa.float()
def _UpperCamelCase( self : Dict ):
a__ : List[str] = AutoModelForSeqaSeqLM.from_pretrained("t5-small" , load_in_abit=lowerCamelCase__ , device_map="auto" )
self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa )
@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class A__ ( unittest.TestCase ):
"""simple docstring"""
@classmethod
def _UpperCamelCase( cls : str ):
a__ : Dict = "t5-small"
a__ : List[Any] = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense
a__ : int = AutoTokenizer.from_pretrained(cls.model_name )
a__ : str = "Translate in German: Hello, my dog is cute"
def _UpperCamelCase( self : Optional[int] ):
gc.collect()
torch.cuda.empty_cache()
def _UpperCamelCase( self : Optional[int] ):
from transformers import TaForConditionalGeneration
a__ : List[Any] = TaForConditionalGeneration._keep_in_fpaa_modules
a__ : Optional[Any] = None
# test with `t5-small`
a__ : Any = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
a__ : Dict = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
a__ : int = model.generate(**lowerCamelCase__ )
# test with `flan-t5-small`
a__ : Dict = TaForConditionalGeneration.from_pretrained(
self.dense_act_model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
a__ : Dict = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
a__ : Any = model.generate(**lowerCamelCase__ )
a__ : Union[str, Any] = modules
def _UpperCamelCase( self : List[Any] ):
import bitsandbytes as bnb
from transformers import TaForConditionalGeneration
# test with `t5-small`
a__ : List[str] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
# there was a bug with decoders - this test checks that it is fixed
self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) )
a__ : Union[str, Any] = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
a__ : int = model.generate(**lowerCamelCase__ )
# test with `flan-t5-small`
a__ : int = TaForConditionalGeneration.from_pretrained(
self.dense_act_model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
a__ : Any = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 )
a__ : Optional[int] = model.generate(**lowerCamelCase__ )
class A__ ( A__ ):
"""simple docstring"""
def _UpperCamelCase( self : List[str] ):
super().setUp()
# model_name
a__ : Union[str, Any] = "bigscience/bloom-560m"
a__ : Union[str, Any] = "t5-small"
# Different types of model
a__ : int = AutoModel.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
# Sequence classification model
a__ : Dict = AutoModelForSequenceClassification.from_pretrained(
self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
# CausalLM model
a__ : str = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
# Seq2seq model
a__ : Dict = AutoModelForSeqaSeqLM.from_pretrained(
self.seq_to_seq_name , load_in_abit=lowerCamelCase__ , device_map="auto" )
def _UpperCamelCase( self : List[Any] ):
del self.base_model
del self.sequence_model
del self.model_abit
del self.seq_to_seq_model
gc.collect()
torch.cuda.empty_cache()
def _UpperCamelCase( self : Union[str, Any] ):
from bitsandbytes.nn import Paramsabit
self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit )
# Other heads should be nn.Parameter
self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter )
self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter )
self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter )
class A__ ( A__ ):
"""simple docstring"""
def _UpperCamelCase( self : Dict ):
super().setUp()
def _UpperCamelCase( self : int ):
del self.pipe
gc.collect()
torch.cuda.empty_cache()
def _UpperCamelCase( self : Tuple ):
a__ : int = pipeline(
"text-generation" , model=self.model_name , model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , )
# Real second forward pass
a__ : Tuple = self.pipe(self.input_text )
self.assertIn(pipeline_output[0]["generated_text"] , self.EXPECTED_OUTPUTS )
@require_torch_multi_gpu
class A__ ( A__ ):
"""simple docstring"""
def _UpperCamelCase( self : Tuple ):
super().setUp()
def _UpperCamelCase( self : List[Any] ):
a__ : str = AutoModelForCausalLM.from_pretrained(
self.model_name , load_in_abit=lowerCamelCase__ , device_map="balanced" )
# Check correct device map
self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} )
# Check that inference pass works on the model
a__ : List[Any] = self.tokenizer(self.input_text , return_tensors="pt" )
# Second real batch
a__ : List[Any] = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 )
self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=lowerCamelCase__ ) , self.EXPECTED_OUTPUTS )
class A__ ( A__ ):
"""simple docstring"""
def _UpperCamelCase( self : Dict ):
a__ : Any = "facebook/opt-350m"
super().setUp()
def _UpperCamelCase( self : int ):
if version.parse(importlib.metadata.version("bitsandbytes" ) ) < version.parse("0.37.0" ):
return
# Step 1: freeze all parameters
a__ : Tuple = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ )
self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} )
for param in model.parameters():
a__ : Any = False # freeze the model - train adapters later
if param.ndim == 1:
# cast the small parameters (e.g. layernorm) to fp32 for stability
a__ : Tuple = param.data.to(torch.floataa )
# Step 2: add adapters
for _, module in model.named_modules():
if "OPTAttention" in repr(type(lowerCamelCase__ ) ):
a__ : Dict = LoRALayer(module.q_proj , rank=16 )
a__ : List[Any] = LoRALayer(module.k_proj , rank=16 )
a__ : List[Any] = LoRALayer(module.v_proj , rank=16 )
# Step 3: dummy batch
a__ : Dict = self.tokenizer("Test batch " , return_tensors="pt" ).to(0 )
# Step 4: Check if the gradient is not None
with torch.cuda.amp.autocast():
a__ : Optional[Any] = model.forward(**lowerCamelCase__ )
out.logits.norm().backward()
for module in model.modules():
if isinstance(lowerCamelCase__ , lowerCamelCase__ ):
self.assertTrue(module.adapter[1].weight.grad is not None )
self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 )
elif isinstance(lowerCamelCase__ , nn.Embedding ):
self.assertTrue(module.weight.grad is None )
class A__ ( A__ ):
"""simple docstring"""
_lowercase = 'gpt2-xl'
_lowercase = 3.31_91_85_48_54_15_21_87
| 37 | """simple docstring"""
import contextlib
import importlib
import io
import unittest
import transformers
# Try to import everything from transformers to ensure every object can be loaded.
from transformers import * # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available
if is_torch_available():
from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification
if is_tf_available():
from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification
if is_flax_available():
from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification
lowerCAmelCase_ = DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co
lowerCAmelCase_ = '''main'''
# Default branch name
lowerCAmelCase_ = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
lowerCAmelCase_ = '''aaaaaaa'''
# This commit does not exist, so we should 404.
lowerCAmelCase_ = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
lowerCAmelCase_ = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''
@contextlib.contextmanager
def lowerCamelCase_()-> int:
print("""Welcome!""" )
yield
print("""Bye!""" )
@contextlib.contextmanager
def lowerCamelCase_()-> Dict:
print("""Bonjour!""" )
yield
print("""Au revoir!""" )
class _snake_case ( unittest.TestCase ):
"""simple docstring"""
def _lowerCAmelCase ( self : Optional[int]):
"""simple docstring"""
assert transformers.__spec__ is not None
assert importlib.util.find_spec("""transformers""") is not None
class _snake_case ( unittest.TestCase ):
"""simple docstring"""
@unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO)
def _lowerCAmelCase ( self : str , _A : str):
"""simple docstring"""
with ContextManagers([]):
print("""Transformers are awesome!""")
# The print statement adds a new line at the end of the output
self.assertEqual(mock_stdout.getvalue() , """Transformers are awesome!\n""")
@unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO)
def _lowerCAmelCase ( self : Any , _A : int):
"""simple docstring"""
with ContextManagers([context_en()]):
print("""Transformers are awesome!""")
# The output should be wrapped with an English welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , """Welcome!\nTransformers are awesome!\nBye!\n""")
@unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO)
def _lowerCAmelCase ( self : str , _A : List[Any]):
"""simple docstring"""
with ContextManagers([context_fr(), context_en()]):
print("""Transformers are awesome!""")
# The output should be wrapped with an English and French welcome and goodbye
self.assertEqual(mock_stdout.getvalue() , """Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n""")
@require_torch
def _lowerCAmelCase ( self : Dict):
"""simple docstring"""
self.assertEqual(find_labels(_A) , ["""labels"""])
self.assertEqual(find_labels(_A) , ["""labels""", """next_sentence_label"""])
self.assertEqual(find_labels(_A) , ["""start_positions""", """end_positions"""])
class _snake_case ( __snake_case ):
"""simple docstring"""
pass
self.assertEqual(find_labels(_A) , ["""labels"""])
@require_tf
def _lowerCAmelCase ( self : Union[str, Any]):
"""simple docstring"""
self.assertEqual(find_labels(_A) , ["""labels"""])
self.assertEqual(find_labels(_A) , ["""labels""", """next_sentence_label"""])
self.assertEqual(find_labels(_A) , ["""start_positions""", """end_positions"""])
class _snake_case ( __snake_case ):
"""simple docstring"""
pass
self.assertEqual(find_labels(_A) , ["""labels"""])
@require_flax
def _lowerCAmelCase ( self : Optional[int]):
"""simple docstring"""
self.assertEqual(find_labels(_A) , [])
self.assertEqual(find_labels(_A) , [])
self.assertEqual(find_labels(_A) , [])
class _snake_case ( __snake_case ):
"""simple docstring"""
pass
self.assertEqual(find_labels(_A) , [])
| 338 | 0 |
'''simple docstring'''
from ....configuration_utils import PretrainedConfig
from ....utils import logging
UpperCamelCase_ = logging.get_logger(__name__)
UpperCamelCase_ = {
"""speechbrain/m-ctc-t-large""": """https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json""",
# See all M-CTC-T models at https://huggingface.co/models?filter=mctct
}
class __SCREAMING_SNAKE_CASE ( lowercase__ ):
lowerCamelCase_ = 'mctct'
def __init__( self : Any , UpperCAmelCase__ : str=8065 , UpperCAmelCase__ : str=1536 , UpperCAmelCase__ : int=36 , UpperCAmelCase__ : Union[str, Any]=6144 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : str=384 , UpperCAmelCase__ : List[str]=920 , UpperCAmelCase__ : Dict=1E-5 , UpperCAmelCase__ : Any=0.3 , UpperCAmelCase__ : int="relu" , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : Optional[Any]=0.3 , UpperCAmelCase__ : Dict=0.3 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Optional[Any]=0.3 , UpperCAmelCase__ : int=1 , UpperCAmelCase__ : Dict=(7,) , UpperCAmelCase__ : Any=(3,) , UpperCAmelCase__ : Union[str, Any]=80 , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : List[str]="sum" , UpperCAmelCase__ : Optional[Any]=False , **UpperCAmelCase__ : Dict , ):
'''simple docstring'''
super().__init__(**UpperCAmelCase__ , pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ )
lowercase : str =vocab_size
lowercase : int =hidden_size
lowercase : Union[str, Any] =num_hidden_layers
lowercase : Optional[Any] =intermediate_size
lowercase : Tuple =num_attention_heads
lowercase : Tuple =attention_head_dim
lowercase : str =max_position_embeddings
lowercase : str =layer_norm_eps
lowercase : int =layerdrop
lowercase : Dict =hidden_act
lowercase : List[str] =initializer_range
lowercase : Optional[Any] =hidden_dropout_prob
lowercase : Dict =attention_probs_dropout_prob
lowercase : Dict =pad_token_id
lowercase : Union[str, Any] =bos_token_id
lowercase : Optional[int] =eos_token_id
lowercase : Optional[Any] =conv_glu_dim
lowercase : Any =conv_dropout
lowercase : int =num_conv_layers
lowercase : Optional[Any] =input_feat_per_channel
lowercase : Optional[int] =input_channels
lowercase : List[str] =conv_channels
lowercase : Optional[Any] =ctc_loss_reduction
lowercase : Optional[Any] =ctc_zero_infinity
# prevents config testing fail with exporting to json
lowercase : Optional[int] =list(UpperCAmelCase__ )
lowercase : Optional[Any] =list(UpperCAmelCase__ )
if len(self.conv_kernel ) != self.num_conv_layers:
raise ValueError(
'''Configuration for convolutional module is incorrect. '''
'''It is required that `len(config.conv_kernel)` == `config.num_conv_layers` '''
F'''but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, '''
F'''`config.num_conv_layers = {self.num_conv_layers}`.''' )
| 88 |
'''simple docstring'''
from typing import List, Optional, Tuple, Union
import torch
from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __SCREAMING_SNAKE_CASE ( lowercase__ ):
def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int ):
'''simple docstring'''
super().__init__()
# make sure scheduler can always be converted to DDIM
lowercase : Any =DDIMScheduler.from_config(scheduler.config )
self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ )
@torch.no_grad()
def __call__( self : List[Any] , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : float = 0.0 , UpperCAmelCase__ : int = 50 , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ):
'''simple docstring'''
# Sample gaussian noise to begin loop
if isinstance(self.unet.config.sample_size , UpperCAmelCase__ ):
lowercase : Optional[int] =(
batch_size,
self.unet.config.in_channels,
self.unet.config.sample_size,
self.unet.config.sample_size,
)
else:
lowercase : Optional[int] =(batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)
if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and len(UpperCAmelCase__ ) != batch_size:
raise ValueError(
F'''You have passed a list of generators of length {len(UpperCAmelCase__ )}, but requested an effective batch'''
F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' )
lowercase : str =randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=self.device , dtype=self.unet.dtype )
# set step values
self.scheduler.set_timesteps(UpperCAmelCase__ )
for t in self.progress_bar(self.scheduler.timesteps ):
# 1. predict noise model_output
lowercase : Dict =self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample
# 2. predict previous mean of image x_t-1 and add variance depending on eta
# eta corresponds to η in paper and should be between [0, 1]
# do x_t -> x_t-1
lowercase : Dict =self.scheduler.step(
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , eta=UpperCAmelCase__ , use_clipped_model_output=UpperCAmelCase__ , generator=UpperCAmelCase__ ).prev_sample
lowercase : Optional[Any] =(image / 2 + 0.5).clamp(0 , 1 )
lowercase : Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
lowercase : List[str] =self.numpy_to_pil(UpperCAmelCase__ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=UpperCAmelCase__ )
| 88 | 1 |
def A_ ( a , a , a ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff)
# formula for sum of series
return total
def A_ ( ):
"""simple docstring"""
print(sum_of_series(1 , 1 , 1_0 ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 511 |
import os
import sys
import warnings
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union
import numpy as np
import pyarrow as pa
from .. import config
from ..download.streaming_download_manager import xopen
from ..table import array_cast
from ..utils.file_utils import is_local_path
from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict
if TYPE_CHECKING:
import PIL.Image
from .features import FeatureType
lowerCAmelCase : Optional[List[str]] = None
lowerCAmelCase : Optional[Any] = '<' if sys.byteorder == 'little' else '>'
# Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image
lowerCAmelCase : str = [
np.dtype('|b1'),
np.dtype('|u1'),
np.dtype('<u2'),
np.dtype('>u2'),
np.dtype('<i2'),
np.dtype('>i2'),
np.dtype('<u4'),
np.dtype('>u4'),
np.dtype('<i4'),
np.dtype('>i4'),
np.dtype('<f4'),
np.dtype('>f4'),
np.dtype('<f8'),
np.dtype('>f8'),
]
@dataclass
class _A :
SCREAMING_SNAKE_CASE : bool = True
SCREAMING_SNAKE_CASE : Optional[str] = None
# Automatically constructed
SCREAMING_SNAKE_CASE : ClassVar[str] = "PIL.Image.Image"
SCREAMING_SNAKE_CASE : ClassVar[Any] = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()})
SCREAMING_SNAKE_CASE : str = field(default='''Image''' , init=__magic_name__ , repr=__magic_name__)
def __call__( self ):
"""simple docstring"""
return self.pa_type
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if config.PIL_AVAILABLE:
import PIL.Image
else:
raise ImportError('To support encoding images, please install \'Pillow\'.' )
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : str = np.array(_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return {"path": value, "bytes": None}
elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return {"path": None, "bytes": value}
elif isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ):
# convert the image array to PNG/TIFF bytes
return encode_np_array(_SCREAMING_SNAKE_CASE )
elif isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ):
# convert the PIL image to bytes (default format is PNG/TIFF)
return encode_pil_image(_SCREAMING_SNAKE_CASE )
elif value.get('path' ) is not None and os.path.isfile(value['path'] ):
# we set "bytes": None to not duplicate the data if they're already available locally
return {"bytes": None, "path": value.get('path' )}
elif value.get('bytes' ) is not None or value.get('path' ) is not None:
# store the image bytes, and path is used to infer the image format using the file extension
return {"bytes": value.get('bytes' ), "path": value.get('path' )}
else:
raise ValueError(
f"An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}." )
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ):
"""simple docstring"""
if not self.decode:
raise RuntimeError('Decoding is disabled for this feature. Please use Image(decode=True) instead.' )
if config.PIL_AVAILABLE:
import PIL.Image
else:
raise ImportError('To support decoding images, please install \'Pillow\'.' )
if token_per_repo_id is None:
SCREAMING_SNAKE_CASE_ : Optional[Any] = {}
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = value['path'], value['bytes']
if bytes_ is None:
if path is None:
raise ValueError(f"An image should have one of 'path' or 'bytes' but both are None in {value}." )
else:
if is_local_path(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : List[str] = PIL.Image.open(_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ : List[Any] = path.split('::' )[-1]
try:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = string_to_dict(_SCREAMING_SNAKE_CASE , config.HUB_DATASETS_URL )['repo_id']
SCREAMING_SNAKE_CASE_ : Optional[int] = token_per_repo_id.get(_SCREAMING_SNAKE_CASE )
except ValueError:
SCREAMING_SNAKE_CASE_ : Tuple = None
with xopen(_SCREAMING_SNAKE_CASE , 'rb' , use_auth_token=_SCREAMING_SNAKE_CASE ) as f:
SCREAMING_SNAKE_CASE_ : Any = BytesIO(f.read() )
SCREAMING_SNAKE_CASE_ : Tuple = PIL.Image.open(bytes_ )
else:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = PIL.Image.open(BytesIO(bytes_ ) )
image.load() # to avoid "Too many open files" errors
return image
def UpperCAmelCase ( self ):
"""simple docstring"""
from .features import Value
return (
self
if self.decode
else {
"bytes": Value('binary' ),
"path": Value('string' ),
}
)
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if pa.types.is_string(storage.type ):
SCREAMING_SNAKE_CASE_ : Optional[int] = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() )
SCREAMING_SNAKE_CASE_ : str = pa.StructArray.from_arrays([bytes_array, storage] , ['bytes', 'path'] , mask=storage.is_null() )
elif pa.types.is_binary(storage.type ):
SCREAMING_SNAKE_CASE_ : int = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() )
SCREAMING_SNAKE_CASE_ : Optional[int] = pa.StructArray.from_arrays([storage, path_array] , ['bytes', 'path'] , mask=storage.is_null() )
elif pa.types.is_struct(storage.type ):
if storage.type.get_field_index('bytes' ) >= 0:
SCREAMING_SNAKE_CASE_ : str = storage.field('bytes' )
else:
SCREAMING_SNAKE_CASE_ : Any = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() )
if storage.type.get_field_index('path' ) >= 0:
SCREAMING_SNAKE_CASE_ : Dict = storage.field('path' )
else:
SCREAMING_SNAKE_CASE_ : Dict = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() )
SCREAMING_SNAKE_CASE_ : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=storage.is_null() )
elif pa.types.is_list(storage.type ):
SCREAMING_SNAKE_CASE_ : Optional[Any] = pa.array(
[encode_np_array(np.array(_SCREAMING_SNAKE_CASE ) )['bytes'] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , )
SCREAMING_SNAKE_CASE_ : Any = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() )
SCREAMING_SNAKE_CASE_ : Dict = pa.StructArray.from_arrays(
[bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null() )
return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type )
def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ):
"""simple docstring"""
@no_op_if_value_is_null
def path_to_bytes(_SCREAMING_SNAKE_CASE ):
with xopen(_SCREAMING_SNAKE_CASE , 'rb' ) as f:
SCREAMING_SNAKE_CASE_ : int = f.read()
return bytes_
SCREAMING_SNAKE_CASE_ : Optional[int] = pa.array(
[
(path_to_bytes(x['path'] ) if x['bytes'] is None else x['bytes']) if x is not None else None
for x in storage.to_pylist()
] , type=pa.binary() , )
SCREAMING_SNAKE_CASE_ : Optional[int] = pa.array(
[os.path.basename(_SCREAMING_SNAKE_CASE ) if path is not None else None for path in storage.field('path' ).to_pylist()] , type=pa.string() , )
SCREAMING_SNAKE_CASE_ : Any = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null() )
return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type )
def A_ ( ):
"""simple docstring"""
if config.PIL_AVAILABLE:
import PIL.Image
else:
raise ImportError('To support encoding images, please install \'Pillow\'.' )
global _IMAGE_COMPRESSION_FORMATS
if _IMAGE_COMPRESSION_FORMATS is None:
PIL.Image.init()
SCREAMING_SNAKE_CASE_ : Tuple = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) )
return _IMAGE_COMPRESSION_FORMATS
def A_ ( a ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = BytesIO()
if image.format in list_image_compression_formats():
SCREAMING_SNAKE_CASE_ : Dict = image.format
else:
SCREAMING_SNAKE_CASE_ : Optional[Any] = 'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF'
image.save(a , format=a )
return buffer.getvalue()
def A_ ( a ):
"""simple docstring"""
if hasattr(a , 'filename' ) and image.filename != "":
return {"path": image.filename, "bytes": None}
else:
return {"path": None, "bytes": image_to_bytes(a )}
def A_ ( a ):
"""simple docstring"""
if config.PIL_AVAILABLE:
import PIL.Image
else:
raise ImportError('To support encoding images, please install \'Pillow\'.' )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = array.dtype
SCREAMING_SNAKE_CASE_ : Any = dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER
SCREAMING_SNAKE_CASE_ : Optional[int] = dtype.kind
SCREAMING_SNAKE_CASE_ : str = dtype.itemsize
SCREAMING_SNAKE_CASE_ : Any = None
# Multi-channel array case (only np.dtype("|u1") is allowed)
if array.shape[2:]:
SCREAMING_SNAKE_CASE_ : List[str] = np.dtype('|u1' )
if dtype_kind not in ["u", "i"]:
raise TypeError(
f"Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays." )
if dtype is not dest_dtype:
warnings.warn(f"Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'" )
# Exact match
elif dtype in _VALID_IMAGE_ARRAY_DTPYES:
SCREAMING_SNAKE_CASE_ : Tuple = dtype
else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually)
while dtype_itemsize >= 1:
SCREAMING_SNAKE_CASE_ : int = dtype_byteorder + dtype_kind + str(a )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = np.dtype(a )
if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES:
warnings.warn(f"Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'" )
break
else:
dtype_itemsize //= 2
if dest_dtype is None:
raise TypeError(
f"Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}" )
SCREAMING_SNAKE_CASE_ : List[str] = PIL.Image.fromarray(array.astype(a ) )
return {"path": None, "bytes": image_to_bytes(a )}
def A_ ( a ):
"""simple docstring"""
if config.PIL_AVAILABLE:
import PIL.Image
else:
raise ImportError('To support encoding images, please install \'Pillow\'.' )
if objs:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = first_non_null_value(a )
if isinstance(a , a ):
return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs]
if isinstance(a , np.ndarray ):
SCREAMING_SNAKE_CASE_ : int = no_op_if_value_is_null(a )
return [obj_to_image_dict_func(a ) for obj in objs]
elif isinstance(a , PIL.Image.Image ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] = no_op_if_value_is_null(a )
return [obj_to_image_dict_func(a ) for obj in objs]
else:
return objs
else:
return objs
| 511 | 1 |
'''simple docstring'''
import operator as op
def UpperCAmelCase ( lowerCamelCase_ :List[str] ):
'''simple docstring'''
snake_case_ : Optional[Any] = []
snake_case_ : List[Any] = lambda lowerCamelCase_ , lowerCamelCase_ : int(x / y ) # noqa: E731 integer division operation
snake_case_ : Optional[Any] = {
"""^""": op.pow,
"""*""": op.mul,
"""/""": div,
"""+""": op.add,
"""-""": op.sub,
} # operators & their respective operation
# print table header
print("""Symbol""".center(8 ) , """Action""".center(12 ) , """Stack""" , sep=""" | """ )
print("""-""" * (30 + len(lowerCamelCase_ )) )
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(lowerCamelCase_ ) # append x to stack
# output in tabular format
print(x.rjust(8 ) , ("""push(""" + x + """)""").ljust(12 ) , """,""".join(lowerCamelCase_ ) , sep=""" | """ )
else:
snake_case_ : Any = stack.pop() # pop stack
# output in tabular format
print("""""".rjust(8 ) , ("""pop(""" + b + """)""").ljust(12 ) , """,""".join(lowerCamelCase_ ) , sep=""" | """ )
snake_case_ : int = stack.pop() # pop stack
# output in tabular format
print("""""".rjust(8 ) , ("""pop(""" + a + """)""").ljust(12 ) , """,""".join(lowerCamelCase_ ) , sep=""" | """ )
stack.append(
str(opr[x](int(lowerCamelCase_ ) , int(lowerCamelCase_ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8 ) , ("""push(""" + a + x + b + """)""").ljust(12 ) , """,""".join(lowerCamelCase_ ) , sep=""" | """ , )
return int(stack[0] )
if __name__ == "__main__":
__A : Optional[Any] = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ')
print('\n\tResult = ', solve(Postfix)) | 267 |
'''simple docstring'''
import argparse
import json
import os
import torch
from torch import nn
from transformers import NllbMoeConfig, NllbMoeModel
from transformers.modeling_utils import dtype_byte_size
from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
def UpperCAmelCase ( lowerCamelCase_ :List[Any] ):
'''simple docstring'''
snake_case_ : Tuple = [
"""encoder.version""",
"""decoder.version""",
"""model.encoder.version""",
"""model.decoder.version""",
"""decoder.output_projection.weight""",
"""_float_tensor""",
"""encoder.embed_positions._float_tensor""",
"""decoder.embed_positions._float_tensor""",
]
for k in ignore_keys:
state_dict.pop(lowerCamelCase_ , lowerCamelCase_ )
def UpperCAmelCase ( lowerCamelCase_ :List[Any] ):
'''simple docstring'''
snake_case_ , snake_case_ : Dict = emb.weight.shape
snake_case_ : str = nn.Linear(lowerCamelCase_ , lowerCamelCase_ , bias=lowerCamelCase_ )
snake_case_ : str = emb.weight.data
return lin_layer
def UpperCAmelCase ( lowerCamelCase_ :List[Any] , lowerCamelCase_ :List[str]=None ):
'''simple docstring'''
snake_case_ : Union[str, Any] = {}
for old_key in state_dict.keys():
snake_case_ : Optional[int] = old_key
if "moe_layer.experts." in key:
if expert_idx is not None:
snake_case_ : Dict = key.replace("""moe_layer.experts.0""" , F'''ffn.experts.expert_{expert_idx}''' )
else:
snake_case_ : str = key.replace("""moe_layer.experts.""" , """ffn.experts.expert_""" )
if "gate" in key:
snake_case_ : List[str] = key.replace(""".moe_layer.gate.wg""" , """.ffn.router.classifier""" )
if "fc2" and "experts" not in key:
snake_case_ : Any = key.replace(""".fc2.""" , """.ffn.fc2.""" )
if "fc1" and "experts" not in key:
snake_case_ : str = key.replace(""".fc1.""" , """.ffn.fc1.""" )
if ".encoder_attn." in key:
snake_case_ : str = key.replace(""".encoder_attn.""" , """.cross_attention.""" )
if "encoder_attn_layer_norm" in key:
snake_case_ : List[str] = key.replace("""encoder_attn_layer_norm""" , """cross_attention_layer_norm""" )
if "final_layer_norm" in key:
snake_case_ : Dict = key.replace("""final_layer_norm""" , """ff_layer_norm""" )
snake_case_ : Dict = state_dict[old_key]
return new_dict
def UpperCAmelCase ( lowerCamelCase_ :Tuple , lowerCamelCase_ :Optional[Any] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Any , lowerCamelCase_ :str = WEIGHTS_NAME ):
'''simple docstring'''
snake_case_ : Tuple = []
snake_case_ : Dict = 0
os.makedirs(lowerCamelCase_ , exist_ok=lowerCamelCase_ )
for expert in range(lowerCamelCase_ ):
snake_case_ : Optional[Any] = switch_checkpoint_path + F'''-rank-{expert}.pt'''
if os.path.isfile(lowerCamelCase_ ):
snake_case_ : List[Any] = torch.load(lowerCamelCase_ )["""model"""]
remove_ignore_keys_(lowerCamelCase_ )
snake_case_ : List[str] = rename_fairseq_keys(lowerCamelCase_ , lowerCamelCase_ )
snake_case_ : List[str] = os.path.join(
lowerCamelCase_ , weights_name.replace(""".bin""" , F'''-{len(lowerCamelCase_ )+1:05d}-of-???.bin''' ) )
torch.save(lowerCamelCase_ , lowerCamelCase_ )
sharded_state_dicts.append(expert_state.keys() )
total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size(
expert_state[list(lowerCamelCase_ )[0]].dtype )
# Add the last block
snake_case_ : Tuple = os.path.join(lowerCamelCase_ , weights_name.replace(""".bin""" , F'''-{len(lowerCamelCase_ )+1:05d}-of-???.bin''' ) )
snake_case_ : Tuple = torch.load(switch_checkpoint_path + """-shared.pt""" )["""model"""]
remove_ignore_keys_(lowerCamelCase_ )
snake_case_ : Tuple = rename_fairseq_keys(lowerCamelCase_ , lowerCamelCase_ )
snake_case_ : List[str] = shared_weights["""decoder.embed_tokens.weight"""]
sharded_state_dicts.append(shared_weights.keys() )
# If we only have the shared weights (dummy model/experts saved on the same file)
if len(lowerCamelCase_ ) == 1:
snake_case_ : Union[str, Any] = os.path.join(lowerCamelCase_ , lowerCamelCase_ )
torch.save(lowerCamelCase_ , lowerCamelCase_ )
return {weights_name: sharded_state_dicts[0]}, None
else:
torch.save(lowerCamelCase_ , lowerCamelCase_ )
# Otherwise, let's build the index
snake_case_ : str = {}
for idx, shard in enumerate(lowerCamelCase_ ):
snake_case_ : List[str] = weights_name.replace(""".bin""" , F'''-{idx+1:05d}-of-{len(lowerCamelCase_ ):05d}.bin''' )
snake_case_ : Optional[int] = os.path.join(lowerCamelCase_ , weights_name.replace(""".bin""" , F'''-{idx+1:05d}-of-???.bin''' ) )
os.rename(lowerCamelCase_ , os.path.join(lowerCamelCase_ , lowerCamelCase_ ) )
for key in shard:
snake_case_ : Optional[int] = shard_file
# Add the metadata
snake_case_ : Any = {"""total_size""": total_size}
snake_case_ : int = {"""metadata""": metadata, """weight_map""": weight_map}
with open(os.path.join(lowerCamelCase_ , lowerCamelCase_ ) , """w""" , encoding="""utf-8""" ) as f:
snake_case_ : List[str] = json.dumps(lowerCamelCase_ , indent=2 , sort_keys=lowerCamelCase_ ) + """\n"""
f.write(lowerCamelCase_ )
return metadata, index
if __name__ == "__main__":
__A : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--nllb_moe_checkpoint_path',
default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000',
type=str,
required=False,
help='Path to a directory containing a folder per layer. Follows the original Google format.',
)
parser.add_argument('--dtype', default='float32', type=str, required=False, help='dtype of the saved model')
parser.add_argument(
'--pytorch_dump_folder_path',
default='/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b',
type=str,
required=False,
help='Path to the output pytorch model.',
)
__A : List[str] = parser.parse_args()
__A, __A : List[Any] = shard_on_the_fly(
args.nllb_moe_checkpoint_path,
args.pytorch_dump_folder_path,
128,
args.dtype,
)
__A : Tuple = NllbMoeConfig.from_pretrained(
'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128
)
config.save_pretrained(args.pytorch_dump_folder_path)
__A : List[str] = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path)
print('Done')
model.save_pretrained(args.pytorch_dump_folder_path) | 267 | 1 |
import argparse
import gc
import json
import os
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
_A : int = 16
_A : List[Any] = 32
def _a ( UpperCAmelCase ) -> str:
"""simple docstring"""
return int(x / 2**20 )
class __SCREAMING_SNAKE_CASE :
def __enter__( self : Tuple ) ->Dict:
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
lowerCamelCase__ : Union[str, Any] = torch.cuda.memory_allocated()
return self
def __exit__( self : Optional[Any] , *A : Union[str, Any] ) ->Optional[Any]:
gc.collect()
torch.cuda.empty_cache()
lowerCamelCase__ : Any = torch.cuda.memory_allocated()
lowerCamelCase__ : Dict = torch.cuda.max_memory_allocated()
lowerCamelCase__ : int = bamb(self.end - self.begin )
lowerCamelCase__ : Optional[Any] = bamb(self.peak - self.begin )
# print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
def _a ( UpperCAmelCase , UpperCAmelCase = 16 , UpperCAmelCase = "bert-base-cased" , UpperCAmelCase = 320 , UpperCAmelCase = 160 , ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__ : int = AutoTokenizer.from_pretrained(UpperCAmelCase )
lowerCamelCase__ : Optional[Any] = load_dataset(
'''glue''' , '''mrpc''' , split={'''train''': f"train[:{n_train}]", '''validation''': f"validation[:{n_val}]"} )
def tokenize_function(UpperCAmelCase ):
# max_length=None => use the model max length (it's actually the default)
lowerCamelCase__ : Dict = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=UpperCAmelCase , max_length=UpperCAmelCase )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
lowerCamelCase__ : List[Any] = datasets.map(
UpperCAmelCase , batched=UpperCAmelCase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=UpperCAmelCase )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
lowerCamelCase__ : List[str] = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(UpperCAmelCase ):
# On TPU it's best to pad everything to the same length or training will be very slow.
if accelerator.distributed_type == DistributedType.TPU:
return tokenizer.pad(UpperCAmelCase , padding='''max_length''' , max_length=128 , return_tensors='''pt''' )
return tokenizer.pad(UpperCAmelCase , padding='''longest''' , return_tensors='''pt''' )
# Instantiate dataloaders.
lowerCamelCase__ : List[Any] = DataLoader(
tokenized_datasets['''train'''] , shuffle=UpperCAmelCase , collate_fn=UpperCAmelCase , batch_size=UpperCAmelCase )
lowerCamelCase__ : List[Any] = DataLoader(
tokenized_datasets['''validation'''] , shuffle=UpperCAmelCase , collate_fn=UpperCAmelCase , batch_size=UpperCAmelCase )
return train_dataloader, eval_dataloader
def _a ( UpperCAmelCase , UpperCAmelCase ) -> str:
"""simple docstring"""
# Initialize accelerator
lowerCamelCase__ : Optional[Any] = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
lowerCamelCase__ : Any = config['''lr''']
lowerCamelCase__ : Optional[Any] = int(config['''num_epochs'''] )
lowerCamelCase__ : Union[str, Any] = int(config['''seed'''] )
lowerCamelCase__ : Optional[int] = int(config['''batch_size'''] )
lowerCamelCase__ : Tuple = args.model_name_or_path
set_seed(UpperCAmelCase )
lowerCamelCase__ , lowerCamelCase__ : Dict = get_dataloaders(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , args.n_train , args.n_val )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
lowerCamelCase__ : Optional[int] = AutoModelForSequenceClassification.from_pretrained(UpperCAmelCase , return_dict=UpperCAmelCase )
# Instantiate optimizer
lowerCamelCase__ : List[str] = (
AdamW
if accelerator.state.deepspeed_plugin is None
or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
lowerCamelCase__ : List[Any] = optimizer_cls(params=model.parameters() , lr=UpperCAmelCase )
if accelerator.state.deepspeed_plugin is not None:
lowerCamelCase__ : Union[str, Any] = accelerator.state.deepspeed_plugin.deepspeed_config[
'''gradient_accumulation_steps'''
]
else:
lowerCamelCase__ : List[str] = 1
lowerCamelCase__ : List[Any] = (len(UpperCAmelCase ) * num_epochs) // gradient_accumulation_steps
# Instantiate scheduler
if (
accelerator.state.deepspeed_plugin is None
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
):
lowerCamelCase__ : Any = get_linear_schedule_with_warmup(
optimizer=UpperCAmelCase , num_warmup_steps=0 , num_training_steps=UpperCAmelCase , )
else:
lowerCamelCase__ : Union[str, Any] = DummyScheduler(UpperCAmelCase , total_num_steps=UpperCAmelCase , warmup_num_steps=0 )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Optional[int] = accelerator.prepare(
UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
# We need to keep track of how many total steps we have iterated over
lowerCamelCase__ : int = 0
# We also need to keep track of the stating epoch so files are named properly
lowerCamelCase__ : Tuple = 0
# Now we train the model
lowerCamelCase__ : Any = {}
for epoch in range(UpperCAmelCase , UpperCAmelCase ):
with TorchTracemalloc() as tracemalloc:
model.train()
for step, batch in enumerate(UpperCAmelCase ):
lowerCamelCase__ : Any = model(**UpperCAmelCase )
lowerCamelCase__ : Union[str, Any] = outputs.loss
lowerCamelCase__ : Union[str, Any] = loss / gradient_accumulation_steps
accelerator.backward(UpperCAmelCase )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
# Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
accelerator.print('''Memory before entering the train : {}'''.format(bamb(tracemalloc.begin ) ) )
accelerator.print('''Memory consumed at the end of the train (end-begin): {}'''.format(tracemalloc.used ) )
accelerator.print('''Peak Memory consumed during the train (max-begin): {}'''.format(tracemalloc.peaked ) )
accelerator.print(
'''Total Peak Memory consumed during the train (max): {}'''.format(
tracemalloc.peaked + bamb(tracemalloc.begin ) ) )
lowerCamelCase__ : Any = tracemalloc.peaked + bamb(tracemalloc.begin )
if args.peak_memory_upper_bound is not None:
assert (
train_total_peak_memory[f"epoch-{epoch}"] <= args.peak_memory_upper_bound
), "Peak memory usage exceeded the upper bound"
accelerator.wait_for_everyone()
if accelerator.is_main_process:
with open(os.path.join(args.output_dir , '''peak_memory_utilization.json''' ) , '''w''' ) as f:
json.dump(UpperCAmelCase , UpperCAmelCase )
def _a ( ) -> Dict:
"""simple docstring"""
lowerCamelCase__ : Dict = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' )
parser.add_argument(
'''--model_name_or_path''' , type=UpperCAmelCase , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=UpperCAmelCase , )
parser.add_argument(
'''--output_dir''' , type=UpperCAmelCase , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , )
parser.add_argument(
'''--peak_memory_upper_bound''' , type=UpperCAmelCase , default=UpperCAmelCase , help='''The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.''' , )
parser.add_argument(
'''--n_train''' , type=UpperCAmelCase , default=320 , help='''Number of training examples to use.''' , )
parser.add_argument(
'''--n_val''' , type=UpperCAmelCase , default=160 , help='''Number of validation examples to use.''' , )
parser.add_argument(
'''--num_epochs''' , type=UpperCAmelCase , default=1 , help='''Number of train epochs.''' , )
lowerCamelCase__ : Tuple = parser.parse_args()
lowerCamelCase__ : int = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16}
training_function(UpperCAmelCase , UpperCAmelCase )
if __name__ == "__main__":
main()
| 315 |
import unittest
from diffusers.models.unet_ad_blocks import * # noqa F403
from diffusers.utils import torch_device
from .test_unet_blocks_common import UNetBlockTesterMixin
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Dict = DownBlockaD # noqa F405
_UpperCAmelCase : List[Any] = "down"
def __lowerCamelCase ( self : Optional[Any] ) ->List[str]:
lowerCamelCase__ : List[str] = [-0.02_32, -0.98_69, 0.80_54, -0.06_37, -0.16_88, -1.42_64, 0.44_70, -1.33_94, 0.09_04]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Tuple = ResnetDownsampleBlockaD # noqa F405
_UpperCAmelCase : Dict = "down"
def __lowerCamelCase ( self : Optional[Any] ) ->int:
lowerCamelCase__ : int = [0.07_10, 0.24_10, -0.73_20, -1.07_57, -1.13_43, 0.35_40, -0.01_33, -0.25_76, 0.09_48]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : str = AttnDownBlockaD # noqa F405
_UpperCAmelCase : Dict = "down"
def __lowerCamelCase ( self : Union[str, Any] ) ->List[str]:
lowerCamelCase__ : List[Any] = [0.06_36, 0.89_64, -0.62_34, -1.01_31, 0.08_44, 0.49_35, 0.34_37, 0.09_11, -0.29_57]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : List[Any] = CrossAttnDownBlockaD # noqa F405
_UpperCAmelCase : int = "down"
def __lowerCamelCase ( self : List[str] ) ->int:
lowerCamelCase__ , lowerCamelCase__ : Any = super().prepare_init_args_and_inputs_for_common()
lowerCamelCase__ : Optional[Any] = 3_2
return init_dict, inputs_dict
def __lowerCamelCase ( self : Dict ) ->List[Any]:
lowerCamelCase__ : Optional[Any] = [0.22_38, -0.73_96, -0.22_55, -0.38_29, 0.19_25, 1.16_65, 0.06_03, -0.72_95, 0.19_83]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : str = SimpleCrossAttnDownBlockaD # noqa F405
_UpperCAmelCase : Union[str, Any] = "down"
@property
def __lowerCamelCase ( self : Any ) ->Union[str, Any]:
return super().get_dummy_input(include_encoder_hidden_states=A )
def __lowerCamelCase ( self : Optional[Any] ) ->List[str]:
lowerCamelCase__ , lowerCamelCase__ : List[str] = super().prepare_init_args_and_inputs_for_common()
lowerCamelCase__ : Optional[int] = 3_2
return init_dict, inputs_dict
@unittest.skipIf(torch_device == '''mps''' , '''MPS result is not consistent''' )
def __lowerCamelCase ( self : Optional[Any] ) ->Tuple:
lowerCamelCase__ : Optional[Any] = [0.79_21, -0.09_92, -0.19_62, -0.76_95, -0.42_42, 0.78_04, 0.47_37, 0.27_65, 0.33_38]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Optional[int] = SkipDownBlockaD # noqa F405
_UpperCAmelCase : List[Any] = "down"
@property
def __lowerCamelCase ( self : Union[str, Any] ) ->List[str]:
return super().get_dummy_input(include_skip_sample=A )
def __lowerCamelCase ( self : str ) ->int:
lowerCamelCase__ : Optional[int] = [-0.08_45, -0.20_87, -0.24_65, 0.09_71, 0.19_00, -0.04_84, 0.26_64, 0.41_79, 0.50_69]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Any = AttnSkipDownBlockaD # noqa F405
_UpperCAmelCase : Any = "down"
@property
def __lowerCamelCase ( self : Optional[Any] ) ->Optional[Any]:
return super().get_dummy_input(include_skip_sample=A )
def __lowerCamelCase ( self : Any ) ->Dict:
lowerCamelCase__ : Any = [0.55_39, 0.16_09, 0.49_24, 0.05_37, -0.19_95, 0.40_50, 0.09_79, -0.27_21, -0.06_42]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Dict = DownEncoderBlockaD # noqa F405
_UpperCAmelCase : Dict = "down"
@property
def __lowerCamelCase ( self : List[Any] ) ->str:
return super().get_dummy_input(include_temb=A )
def __lowerCamelCase ( self : str ) ->Optional[Any]:
lowerCamelCase__ : List[Any] = {
'''in_channels''': 3_2,
'''out_channels''': 3_2,
}
lowerCamelCase__ : List[Any] = self.dummy_input
return init_dict, inputs_dict
def __lowerCamelCase ( self : Dict ) ->int:
lowerCamelCase__ : str = [1.11_02, 0.53_02, 0.48_72, -0.00_23, -0.80_42, 0.04_83, -0.34_89, -0.56_32, 0.76_26]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Tuple = AttnDownEncoderBlockaD # noqa F405
_UpperCAmelCase : str = "down"
@property
def __lowerCamelCase ( self : str ) ->List[Any]:
return super().get_dummy_input(include_temb=A )
def __lowerCamelCase ( self : Tuple ) ->List[str]:
lowerCamelCase__ : Optional[Any] = {
'''in_channels''': 3_2,
'''out_channels''': 3_2,
}
lowerCamelCase__ : List[Any] = self.dummy_input
return init_dict, inputs_dict
def __lowerCamelCase ( self : Optional[int] ) ->Union[str, Any]:
lowerCamelCase__ : Union[str, Any] = [0.89_66, -0.14_86, 0.85_68, 0.81_41, -0.90_46, -0.13_42, -0.09_72, -0.74_17, 0.15_38]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Union[str, Any] = UNetMidBlockaD # noqa F405
_UpperCAmelCase : Tuple = "mid"
def __lowerCamelCase ( self : Optional[int] ) ->Dict:
lowerCamelCase__ : Any = {
'''in_channels''': 3_2,
'''temb_channels''': 1_2_8,
}
lowerCamelCase__ : Optional[Any] = self.dummy_input
return init_dict, inputs_dict
def __lowerCamelCase ( self : Tuple ) ->List[str]:
lowerCamelCase__ : Tuple = [-0.10_62, 1.72_48, 0.34_94, 1.45_69, -0.09_10, -1.24_21, -0.99_84, 0.67_36, 1.00_28]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Union[str, Any] = UNetMidBlockaDCrossAttn # noqa F405
_UpperCAmelCase : List[str] = "mid"
def __lowerCamelCase ( self : List[str] ) ->List[str]:
lowerCamelCase__ , lowerCamelCase__ : Any = super().prepare_init_args_and_inputs_for_common()
lowerCamelCase__ : List[str] = 3_2
return init_dict, inputs_dict
def __lowerCamelCase ( self : Dict ) ->Tuple:
lowerCamelCase__ : int = [0.01_87, 2.42_20, 0.44_84, 1.12_03, -0.61_21, -1.51_22, -0.82_70, 0.78_51, 1.83_35]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Optional[Any] = UNetMidBlockaDSimpleCrossAttn # noqa F405
_UpperCAmelCase : int = "mid"
@property
def __lowerCamelCase ( self : List[str] ) ->List[str]:
return super().get_dummy_input(include_encoder_hidden_states=A )
def __lowerCamelCase ( self : str ) ->Any:
lowerCamelCase__ , lowerCamelCase__ : Any = super().prepare_init_args_and_inputs_for_common()
lowerCamelCase__ : Optional[int] = 3_2
return init_dict, inputs_dict
def __lowerCamelCase ( self : List[Any] ) ->Optional[Any]:
lowerCamelCase__ : List[Any] = [0.71_43, 1.99_74, 0.54_48, 1.39_77, 0.12_82, -1.12_37, -1.42_38, 0.55_30, 0.88_80]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Tuple = UpBlockaD # noqa F405
_UpperCAmelCase : Any = "up"
@property
def __lowerCamelCase ( self : Union[str, Any] ) ->Optional[int]:
return super().get_dummy_input(include_res_hidden_states_tuple=A )
def __lowerCamelCase ( self : List[Any] ) ->List[Any]:
lowerCamelCase__ : Optional[Any] = [-0.20_41, -0.41_65, -0.30_22, 0.00_41, -0.66_28, -0.70_53, 0.19_28, -0.03_25, 0.05_23]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Union[str, Any] = ResnetUpsampleBlockaD # noqa F405
_UpperCAmelCase : Optional[Any] = "up"
@property
def __lowerCamelCase ( self : Union[str, Any] ) ->List[Any]:
return super().get_dummy_input(include_res_hidden_states_tuple=A )
def __lowerCamelCase ( self : List[Any] ) ->List[str]:
lowerCamelCase__ : List[Any] = [0.22_87, 0.35_49, -0.13_46, 0.47_97, -0.17_15, -0.96_49, 0.73_05, -0.58_64, -0.62_44]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : List[Any] = CrossAttnUpBlockaD # noqa F405
_UpperCAmelCase : Optional[Any] = "up"
@property
def __lowerCamelCase ( self : Union[str, Any] ) ->Dict:
return super().get_dummy_input(include_res_hidden_states_tuple=A )
def __lowerCamelCase ( self : Optional[int] ) ->Any:
lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = super().prepare_init_args_and_inputs_for_common()
lowerCamelCase__ : Tuple = 3_2
return init_dict, inputs_dict
def __lowerCamelCase ( self : Optional[int] ) ->Optional[Any]:
lowerCamelCase__ : Dict = [-0.14_03, -0.35_15, -0.04_20, -0.14_25, 0.31_67, 0.50_94, -0.21_81, 0.59_31, 0.55_82]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Optional[Any] = SimpleCrossAttnUpBlockaD # noqa F405
_UpperCAmelCase : Any = "up"
@property
def __lowerCamelCase ( self : Tuple ) ->int:
return super().get_dummy_input(include_res_hidden_states_tuple=A , include_encoder_hidden_states=A )
def __lowerCamelCase ( self : Any ) ->List[str]:
lowerCamelCase__ , lowerCamelCase__ : Any = super().prepare_init_args_and_inputs_for_common()
lowerCamelCase__ : Tuple = 3_2
return init_dict, inputs_dict
def __lowerCamelCase ( self : Tuple ) ->List[str]:
lowerCamelCase__ : str = [0.26_45, 0.14_80, 0.09_09, 0.80_44, -0.97_58, -0.90_83, 0.09_94, -1.14_53, -0.74_02]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : List[Any] = AttnUpBlockaD # noqa F405
_UpperCAmelCase : Dict = "up"
@property
def __lowerCamelCase ( self : Optional[int] ) ->int:
return super().get_dummy_input(include_res_hidden_states_tuple=A )
@unittest.skipIf(torch_device == '''mps''' , '''MPS result is not consistent''' )
def __lowerCamelCase ( self : Optional[int] ) ->List[str]:
lowerCamelCase__ : Optional[int] = [0.09_79, 0.13_26, 0.00_21, 0.06_59, 0.22_49, 0.00_59, 0.11_32, 0.59_52, 0.10_33]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : str = SkipUpBlockaD # noqa F405
_UpperCAmelCase : List[Any] = "up"
@property
def __lowerCamelCase ( self : Dict ) ->str:
return super().get_dummy_input(include_res_hidden_states_tuple=A )
def __lowerCamelCase ( self : List[str] ) ->Optional[Any]:
lowerCamelCase__ : List[str] = [-0.08_93, -0.12_34, -0.15_06, -0.03_32, 0.01_23, -0.02_11, 0.05_66, 0.01_43, 0.03_62]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : int = AttnSkipUpBlockaD # noqa F405
_UpperCAmelCase : Optional[Any] = "up"
@property
def __lowerCamelCase ( self : List[str] ) ->str:
return super().get_dummy_input(include_res_hidden_states_tuple=A )
def __lowerCamelCase ( self : str ) ->Tuple:
lowerCamelCase__ : str = [0.03_61, 0.06_17, 0.27_87, -0.03_50, 0.03_42, 0.34_21, -0.08_43, 0.09_13, 0.30_15]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : Dict = UpDecoderBlockaD # noqa F405
_UpperCAmelCase : Tuple = "up"
@property
def __lowerCamelCase ( self : int ) ->int:
return super().get_dummy_input(include_temb=A )
def __lowerCamelCase ( self : int ) ->Any:
lowerCamelCase__ : List[str] = {'''in_channels''': 3_2, '''out_channels''': 3_2}
lowerCamelCase__ : Union[str, Any] = self.dummy_input
return init_dict, inputs_dict
def __lowerCamelCase ( self : List[Any] ) ->Union[str, Any]:
lowerCamelCase__ : Union[str, Any] = [0.44_04, 0.19_98, -0.98_86, -0.33_20, -0.31_28, -0.70_34, -0.69_55, -0.23_38, -0.31_37]
super().test_output(A )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ):
_UpperCAmelCase : str = AttnUpDecoderBlockaD # noqa F405
_UpperCAmelCase : Union[str, Any] = "up"
@property
def __lowerCamelCase ( self : Dict ) ->Union[str, Any]:
return super().get_dummy_input(include_temb=A )
def __lowerCamelCase ( self : Any ) ->int:
lowerCamelCase__ : Optional[int] = {'''in_channels''': 3_2, '''out_channels''': 3_2}
lowerCamelCase__ : List[Any] = self.dummy_input
return init_dict, inputs_dict
def __lowerCamelCase ( self : Optional[Any] ) ->int:
lowerCamelCase__ : Tuple = [0.67_38, 0.44_91, 0.10_55, 1.07_10, 0.73_16, 0.33_39, 0.33_52, 0.10_23, 0.35_68]
super().test_output(A )
| 315 | 1 |
"""simple docstring"""
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from torchvision.transforms import functional as F
from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection
from transformers.utils import logging
logging.set_verbosity_info()
lowerCAmelCase : Optional[Any] = logging.get_logger(__name__)
# here we list all keys to be renamed (original name on the left, our name on the right)
lowerCAmelCase : Optional[Any] = []
for i in range(6):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append(
(F"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", F"""encoder.layers.{i}.self_attn.out_proj.weight""")
)
rename_keys.append(
(F"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", F"""encoder.layers.{i}.self_attn.out_proj.bias""")
)
rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.weight""", F"""encoder.layers.{i}.fc1.weight"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.bias""", F"""encoder.layers.{i}.fc1.bias"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.weight""", F"""encoder.layers.{i}.fc2.weight"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.bias""", F"""encoder.layers.{i}.fc2.bias"""))
rename_keys.append(
(F"""transformer.encoder.layers.{i}.norm1.weight""", F"""encoder.layers.{i}.self_attn_layer_norm.weight""")
)
rename_keys.append((F"""transformer.encoder.layers.{i}.norm1.bias""", F"""encoder.layers.{i}.self_attn_layer_norm.bias"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.weight""", F"""encoder.layers.{i}.final_layer_norm.weight"""))
rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.bias""", F"""encoder.layers.{i}.final_layer_norm.bias"""))
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
rename_keys.append(
(F"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", F"""decoder.layers.{i}.self_attn.out_proj.weight""")
)
rename_keys.append(
(F"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", F"""decoder.layers.{i}.self_attn.out_proj.bias""")
)
rename_keys.append(
(
F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""",
F"""decoder.layers.{i}.encoder_attn.out_proj.weight""",
)
)
rename_keys.append(
(
F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""",
F"""decoder.layers.{i}.encoder_attn.out_proj.bias""",
)
)
rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.weight""", F"""decoder.layers.{i}.fc1.weight"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.bias""", F"""decoder.layers.{i}.fc1.bias"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.weight""", F"""decoder.layers.{i}.fc2.weight"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.bias""", F"""decoder.layers.{i}.fc2.bias"""))
rename_keys.append(
(F"""transformer.decoder.layers.{i}.norm1.weight""", F"""decoder.layers.{i}.self_attn_layer_norm.weight""")
)
rename_keys.append((F"""transformer.decoder.layers.{i}.norm1.bias""", F"""decoder.layers.{i}.self_attn_layer_norm.bias"""))
rename_keys.append(
(F"""transformer.decoder.layers.{i}.norm2.weight""", F"""decoder.layers.{i}.encoder_attn_layer_norm.weight""")
)
rename_keys.append(
(F"""transformer.decoder.layers.{i}.norm2.bias""", F"""decoder.layers.{i}.encoder_attn_layer_norm.bias""")
)
rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.weight""", F"""decoder.layers.{i}.final_layer_norm.weight"""))
rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.bias""", F"""decoder.layers.{i}.final_layer_norm.bias"""))
# convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads
rename_keys.extend(
[
("""input_proj.weight""", """input_projection.weight"""),
("""input_proj.bias""", """input_projection.bias"""),
("""query_embed.weight""", """query_position_embeddings.weight"""),
("""transformer.encoder.norm.weight""", """encoder.layernorm.weight"""),
("""transformer.encoder.norm.bias""", """encoder.layernorm.bias"""),
("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""),
("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""),
("""class_embed.weight""", """class_labels_classifier.weight"""),
("""class_embed.bias""", """class_labels_classifier.bias"""),
("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""),
("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""),
("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""),
("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""),
("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""),
("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""),
]
)
def a__ ( snake_case__ , snake_case__ , snake_case__ ) -> List[str]:
lowerCamelCase = state_dict.pop(snake_case__ )
lowerCamelCase = val
def a__ ( snake_case__ ) -> List[str]:
lowerCamelCase = OrderedDict()
for key, value in state_dict.items():
if "backbone.0.body" in key:
lowerCamelCase = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" )
lowerCamelCase = value
else:
lowerCamelCase = value
return new_state_dict
def a__ ( snake_case__ ) -> List[str]:
lowerCamelCase = """"""
# first: transformer encoder
for i in range(6 ):
# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
lowerCamelCase = state_dict.pop(F'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight' )
lowerCamelCase = state_dict.pop(F'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias' )
# next, add query, keys and values (in that order) to the state dict
lowerCamelCase = in_proj_weight[:2_56, :]
lowerCamelCase = in_proj_bias[:2_56]
lowerCamelCase = in_proj_weight[2_56:5_12, :]
lowerCamelCase = in_proj_bias[2_56:5_12]
lowerCamelCase = in_proj_weight[-2_56:, :]
lowerCamelCase = in_proj_bias[-2_56:]
# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
for i in range(6 ):
# read in weights + bias of input projection layer of self-attention
lowerCamelCase = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight' )
lowerCamelCase = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias' )
# next, add query, keys and values (in that order) to the state dict
lowerCamelCase = in_proj_weight[:2_56, :]
lowerCamelCase = in_proj_bias[:2_56]
lowerCamelCase = in_proj_weight[2_56:5_12, :]
lowerCamelCase = in_proj_bias[2_56:5_12]
lowerCamelCase = in_proj_weight[-2_56:, :]
lowerCamelCase = in_proj_bias[-2_56:]
# read in weights + bias of input projection layer of cross-attention
lowerCamelCase = state_dict.pop(
F'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight' )
lowerCamelCase = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias' )
# next, add query, keys and values (in that order) of cross-attention to the state dict
lowerCamelCase = in_proj_weight_cross_attn[:2_56, :]
lowerCamelCase = in_proj_bias_cross_attn[:2_56]
lowerCamelCase = in_proj_weight_cross_attn[2_56:5_12, :]
lowerCamelCase = in_proj_bias_cross_attn[2_56:5_12]
lowerCamelCase = in_proj_weight_cross_attn[-2_56:, :]
lowerCamelCase = in_proj_bias_cross_attn[-2_56:]
def a__ ( snake_case__ , snake_case__ ) -> str:
lowerCamelCase , lowerCamelCase = image.size
lowerCamelCase = max(snake_case__ , snake_case__ )
lowerCamelCase = 8_00 if """detection""" in checkpoint_url else 10_00
lowerCamelCase = target_max_size / current_max_size
lowerCamelCase = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) )
return resized_image
def a__ ( snake_case__ ) -> List[str]:
lowerCamelCase = F.to_tensor(snake_case__ )
lowerCamelCase = F.normalize(snake_case__ , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] )
return image
@torch.no_grad()
def a__ ( snake_case__ , snake_case__ , snake_case__ ) -> Tuple:
logger.info("""Converting model...""" )
# load original state dict
lowerCamelCase = torch.hub.load_state_dict_from_url(snake_case__ , map_location="""cpu""" )
# rename keys
for src, dest in rename_keys:
rename_key(snake_case__ , snake_case__ , snake_case__ )
lowerCamelCase = rename_backbone_keys(snake_case__ )
# query, key and value matrices need special treatment
read_in_q_k_v(snake_case__ )
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
lowerCamelCase = """model."""
for key in state_dict.copy().keys():
if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ):
lowerCamelCase = state_dict.pop(snake_case__ )
lowerCamelCase = val
# create HuggingFace model and load state dict
lowerCamelCase = TableTransformerConfig(
backbone="""resnet18""" , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , )
if "detection" in checkpoint_url:
lowerCamelCase = 15
lowerCamelCase = 2
lowerCamelCase = {0: """table""", 1: """table rotated"""}
lowerCamelCase = idalabel
lowerCamelCase = {v: k for k, v in idalabel.items()}
else:
lowerCamelCase = 1_25
lowerCamelCase = 6
lowerCamelCase = {
0: """table""",
1: """table column""",
2: """table row""",
3: """table column header""",
4: """table projected row header""",
5: """table spanning cell""",
}
lowerCamelCase = idalabel
lowerCamelCase = {v: k for k, v in idalabel.items()}
lowerCamelCase = DetrImageProcessor(
format="""coco_detection""" , max_size=8_00 if """detection""" in checkpoint_url else 10_00 )
lowerCamelCase = TableTransformerForObjectDetection(snake_case__ )
model.load_state_dict(snake_case__ )
model.eval()
# verify our conversion
lowerCamelCase = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png"""
lowerCamelCase = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=snake_case__ )
lowerCamelCase = Image.open(snake_case__ ).convert("""RGB""" )
lowerCamelCase = normalize(resize(snake_case__ , snake_case__ ) ).unsqueeze(0 )
lowerCamelCase = model(snake_case__ )
if "detection" in checkpoint_url:
lowerCamelCase = (1, 15, 3)
lowerCamelCase = torch.tensor(
[[-6.7897, -16.9985, 6.7937], [-8.0186, -22.2192, 6.9677], [-7.3117, -21.0708, 7.4055]] )
lowerCamelCase = torch.tensor([[0.4867, 0.1767, 0.6732], [0.6718, 0.4479, 0.3830], [0.4716, 0.1760, 0.6364]] )
else:
lowerCamelCase = (1, 1_25, 7)
lowerCamelCase = torch.tensor(
[[-18.1430, -8.3214, 4.8274], [-18.4685, -7.1361, -4.2667], [-26.3693, -9.3429, -4.9962]] )
lowerCamelCase = torch.tensor([[0.4983, 0.5595, 0.9440], [0.4916, 0.6315, 0.5954], [0.6108, 0.8637, 0.1135]] )
assert outputs.logits.shape == expected_shape
assert torch.allclose(outputs.logits[0, :3, :3] , snake_case__ , atol=1E-4 )
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , snake_case__ , atol=1E-4 )
print("""Looks ok!""" )
if pytorch_dump_folder_path is not None:
# Save model and image processor
logger.info(F'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' )
Path(snake_case__ ).mkdir(exist_ok=snake_case__ )
model.save_pretrained(snake_case__ )
image_processor.save_pretrained(snake_case__ )
if push_to_hub:
# Push model to HF hub
logger.info("""Pushing model to the hub...""" )
lowerCamelCase = (
"""microsoft/table-transformer-detection"""
if """detection""" in checkpoint_url
else """microsoft/table-transformer-structure-recognition"""
)
model.push_to_hub(snake_case__ )
image_processor.push_to_hub(snake_case__ )
if __name__ == "__main__":
lowerCAmelCase : str = argparse.ArgumentParser()
parser.add_argument(
"""--checkpoint_url""",
default="""https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth""",
type=str,
choices=[
"""https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth""",
"""https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth""",
],
help="""URL of the Table Transformer checkpoint you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model."""
)
parser.add_argument(
"""--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
)
lowerCAmelCase : int = parser.parse_args()
convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
| 533 |
"""simple docstring"""
import uuid
from typing import Any, Dict, List, Optional, Union
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_tf_available():
import tensorflow as tf
if is_torch_available():
import torch
lowerCAmelCase : List[str] = logging.get_logger(__name__)
class __magic_name__ :
'''simple docstring'''
def __init__( self , _a = None , _a = None , _a=None , _a=None ):
"""simple docstring"""
if not conversation_id:
lowerCamelCase = uuid.uuida()
if past_user_inputs is None:
lowerCamelCase = []
if generated_responses is None:
lowerCamelCase = []
lowerCamelCase = conversation_id
lowerCamelCase = past_user_inputs
lowerCamelCase = generated_responses
lowerCamelCase = text
def __eq__( self , _a ):
"""simple docstring"""
if not isinstance(_a , _a ):
return False
if self.uuid == other.uuid:
return True
return (
self.new_user_input == other.new_user_input
and self.past_user_inputs == other.past_user_inputs
and self.generated_responses == other.generated_responses
)
def _lowerCAmelCase ( self , _a , _a = False ):
"""simple docstring"""
if self.new_user_input:
if overwrite:
logger.warning(
f'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '
f'with: "{text}".' )
lowerCamelCase = text
else:
logger.warning(
f'User input added while unprocessed input was existing: "{self.new_user_input}" new input '
f'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input' )
else:
lowerCamelCase = text
def _lowerCAmelCase ( self ):
"""simple docstring"""
if self.new_user_input:
self.past_user_inputs.append(self.new_user_input )
lowerCamelCase = None
def _lowerCAmelCase ( self , _a ):
"""simple docstring"""
self.generated_responses.append(_a )
def _lowerCAmelCase ( self ):
"""simple docstring"""
for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ):
yield True, user_input
yield False, generated_response
if self.new_user_input:
yield True, self.new_user_input
def __repr__( self ):
"""simple docstring"""
lowerCamelCase = f'Conversation id: {self.uuid} \n'
for is_user, text in self.iter_texts():
lowerCamelCase = """user""" if is_user else """bot"""
output += f'{name} >> {text} \n'
return output
@add_end_docstrings(
UpperCAmelCase__ , R"\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n " , )
class __magic_name__ ( UpperCAmelCase__ ):
'''simple docstring'''
def __init__( self , *_a , **_a ):
"""simple docstring"""
super().__init__(*_a , **_a )
if self.tokenizer.pad_token_id is None:
lowerCamelCase = self.tokenizer.eos_token
def _lowerCAmelCase ( self , _a=None , _a=None , _a=None , **_a ):
"""simple docstring"""
lowerCamelCase = {}
lowerCamelCase = {}
lowerCamelCase = {}
if min_length_for_response is not None:
lowerCamelCase = min_length_for_response
if minimum_tokens is not None:
lowerCamelCase = minimum_tokens
if "max_length" in generate_kwargs:
lowerCamelCase = generate_kwargs["""max_length"""]
# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
if clean_up_tokenization_spaces is not None:
lowerCamelCase = clean_up_tokenization_spaces
if generate_kwargs:
forward_params.update(_a )
return preprocess_params, forward_params, postprocess_params
def __call__( self , _a , _a=0 , **_a ):
"""simple docstring"""
lowerCamelCase = super().__call__(_a , num_workers=_a , **_a )
if isinstance(_a , _a ) and len(_a ) == 1:
return outputs[0]
return outputs
def _lowerCAmelCase ( self , _a , _a=32 ):
"""simple docstring"""
if not isinstance(_a , _a ):
raise ValueError("""ConversationalPipeline, expects Conversation as inputs""" )
if conversation.new_user_input is None:
raise ValueError(
f'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. '
"""Add user inputs with the conversation's `add_user_input` method""" )
if hasattr(self.tokenizer , """_build_conversation_input_ids""" ):
lowerCamelCase = self.tokenizer._build_conversation_input_ids(_a )
else:
# If the tokenizer cannot handle conversations, we default to only the old version
lowerCamelCase = self._legacy_parse_and_tokenize(_a )
if self.framework == "pt":
lowerCamelCase = torch.LongTensor([input_ids] )
elif self.framework == "tf":
lowerCamelCase = tf.constant([input_ids] )
return {"input_ids": input_ids, "conversation": conversation}
def _lowerCAmelCase ( self , _a , _a=10 , **_a ):
"""simple docstring"""
lowerCamelCase = generate_kwargs.get("""max_length""" , self.model.config.max_length )
lowerCamelCase = model_inputs["""input_ids"""].shape[1]
if max_length - minimum_tokens < n:
logger.warning(f'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' )
lowerCamelCase = max_length - minimum_tokens
lowerCamelCase = model_inputs["""input_ids"""][:, -trim:]
if "attention_mask" in model_inputs:
lowerCamelCase = model_inputs["""attention_mask"""][:, -trim:]
lowerCamelCase = model_inputs.pop("""conversation""" )
lowerCamelCase = max_length
lowerCamelCase = self.model.generate(**_a , **_a )
if self.model.config.is_encoder_decoder:
lowerCamelCase = 1
else:
lowerCamelCase = n
return {"output_ids": output_ids[:, start_position:], "conversation": conversation}
def _lowerCAmelCase ( self , _a , _a=True ):
"""simple docstring"""
lowerCamelCase = model_outputs["""output_ids"""]
lowerCamelCase = self.tokenizer.decode(
output_ids[0] , skip_special_tokens=_a , clean_up_tokenization_spaces=_a , )
lowerCamelCase = model_outputs["""conversation"""]
conversation.mark_processed()
conversation.append_response(_a )
return conversation
def _lowerCAmelCase ( self , _a ):
"""simple docstring"""
lowerCamelCase = self.tokenizer.eos_token_id
lowerCamelCase = []
for is_user, text in conversation.iter_texts():
if eos_token_id is not None:
input_ids.extend(self.tokenizer.encode(_a , add_special_tokens=_a ) + [eos_token_id] )
else:
input_ids.extend(self.tokenizer.encode(_a , add_special_tokens=_a ) )
if len(_a ) > self.tokenizer.model_max_length:
lowerCamelCase = input_ids[-self.tokenizer.model_max_length :]
return input_ids
| 533 | 1 |
UpperCamelCase__ ={
'Pillow': 'Pillow',
'accelerate': 'accelerate>=0.11.0',
'compel': 'compel==0.1.8',
'black': 'black~=23.1',
'datasets': 'datasets',
'filelock': 'filelock',
'flax': 'flax>=0.4.1',
'hf-doc-builder': 'hf-doc-builder>=0.3.0',
'huggingface-hub': 'huggingface-hub>=0.13.2',
'requests-mock': 'requests-mock==1.10.0',
'importlib_metadata': 'importlib_metadata',
'invisible-watermark': 'invisible-watermark',
'isort': 'isort>=5.5.4',
'jax': 'jax>=0.2.8,!=0.3.2',
'jaxlib': 'jaxlib>=0.1.65',
'Jinja2': 'Jinja2',
'k-diffusion': 'k-diffusion>=0.0.12',
'torchsde': 'torchsde',
'note_seq': 'note_seq',
'librosa': 'librosa',
'numpy': 'numpy',
'omegaconf': 'omegaconf',
'parameterized': 'parameterized',
'protobuf': 'protobuf>=3.20.3,<4',
'pytest': 'pytest',
'pytest-timeout': 'pytest-timeout',
'pytest-xdist': 'pytest-xdist',
'ruff': 'ruff>=0.0.241',
'safetensors': 'safetensors',
'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
'scipy': 'scipy',
'onnx': 'onnx',
'regex': 'regex!=2019.12.17',
'requests': 'requests',
'tensorboard': 'tensorboard',
'torch': 'torch>=1.4',
'torchvision': 'torchvision',
'transformers': 'transformers>=4.25.1',
'urllib3': 'urllib3<=2.0.0',
} | 249 |
def lowerCamelCase__ (__lowerCamelCase ):
_SCREAMING_SNAKE_CASE : List[Any] = 1
for i in range(1, num + 1 ):
fact *= i
return fact
def lowerCamelCase__ (__lowerCamelCase ):
_SCREAMING_SNAKE_CASE : int = 0
while number > 0:
_SCREAMING_SNAKE_CASE : Optional[int] = number % 10
sum_of_digits += last_digit
_SCREAMING_SNAKE_CASE : int = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def lowerCamelCase__ (__lowerCamelCase = 100 ):
_SCREAMING_SNAKE_CASE : Dict = factorial(__lowerCamelCase )
_SCREAMING_SNAKE_CASE : Tuple = split_and_add(__lowerCamelCase )
return result
if __name__ == "__main__":
print(solution(int(input('Enter the Number: ').strip()))) | 249 | 1 |
"""simple docstring"""
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> list[int]:
'''simple docstring'''
if num <= 0:
raise ValueError("""Input must be a positive integer""" )
lowercase_ = [True] * (num + 1)
lowercase_ = 2
while p * p <= num:
if primes[p]:
for i in range(p * p , num + 1 , __lowerCAmelCase ):
lowercase_ = False
p += 1
return [prime for prime in range(2 , num + 1 ) if primes[prime]]
if __name__ == "__main__":
import doctest
doctest.testmod()
UpperCAmelCase : Optional[int] = int(input("Enter a positive integer: ").strip())
print(prime_sieve_eratosthenes(user_num))
| 100 |
"""simple docstring"""
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> tuple:
'''simple docstring'''
return (data["data"], data["target"])
def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> np.ndarray:
'''simple docstring'''
lowercase_ = XGBRegressor(verbosity=0 , random_state=42 )
xgb.fit(__lowerCAmelCase , __lowerCAmelCase )
# Predict target for test data
lowercase_ = xgb.predict(__lowerCAmelCase )
lowercase_ = predictions.reshape(len(__lowerCAmelCase ) , 1 )
return predictions
def _SCREAMING_SNAKE_CASE () -> None:
'''simple docstring'''
lowercase_ = fetch_california_housing()
lowercase_ , lowercase_ = data_handling(__lowerCAmelCase )
lowercase_ , lowercase_ , lowercase_ , lowercase_ = train_test_split(
__lowerCAmelCase , __lowerCAmelCase , test_size=0.25 , random_state=1 )
lowercase_ = xgboost(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
# Error printing
print(F'''Mean Absolute Error : {mean_absolute_error(__lowerCAmelCase , __lowerCAmelCase )}''' )
print(F'''Mean Square Error : {mean_squared_error(__lowerCAmelCase , __lowerCAmelCase )}''' )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
main()
| 100 | 1 |
"""simple docstring"""
from __future__ import annotations
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class _a :
a_ : int
a_ : int
class _a :
def __init__( self : int , SCREAMING_SNAKE_CASE__ : int ):
lowerCamelCase__ = [[] for _ in range(SCREAMING_SNAKE_CASE__ )]
lowerCamelCase__ = size
def __getitem__( self : List[Any] , SCREAMING_SNAKE_CASE__ : int ):
return iter(self._graph[vertex] )
@property
def _UpperCamelCase ( self : Any ):
return self._size
def _UpperCamelCase ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ):
if weight not in (0, 1):
raise ValueError('Edge weight must be either 0 or 1.' )
if to_vertex < 0 or to_vertex >= self.size:
raise ValueError('Vertex indexes must be in [0; size).' )
self._graph[from_vertex].append(Edge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
def _UpperCamelCase ( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ):
lowerCamelCase__ = deque([start_vertex] )
lowerCamelCase__ = [None] * self.size
lowerCamelCase__ = 0
while queue:
lowerCamelCase__ = queue.popleft()
lowerCamelCase__ = distances[current_vertex]
if current_distance is None:
continue
for edge in self[current_vertex]:
lowerCamelCase__ = current_distance + edge.weight
lowerCamelCase__ = distances[edge.destination_vertex]
if (
isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
and new_distance >= dest_vertex_distance
):
continue
lowerCamelCase__ = new_distance
if edge.weight == 0:
queue.appendleft(edge.destination_vertex )
else:
queue.append(edge.destination_vertex )
if distances[finish_vertex] is None:
raise ValueError('No path from start_vertex to finish_vertex.' )
return distances[finish_vertex]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 510 |
"""simple docstring"""
import os
import sys
_snake_case = os.path.join(os.path.dirname(__file__), "src")
sys.path.append(SRC_DIR)
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoTokenizer,
add_start_docstrings,
)
_snake_case = [
"torch",
"numpy",
"tokenizers",
"filelock",
"requests",
"tqdm",
"regex",
"sentencepiece",
"sacremoses",
"importlib_metadata",
"huggingface_hub",
]
@add_start_docstrings(AutoConfig.__doc__ )
def snake_case ( *_a: str , **_a: int )-> Union[str, Any]:
'''simple docstring'''
return AutoConfig.from_pretrained(*_a , **_a )
@add_start_docstrings(AutoTokenizer.__doc__ )
def snake_case ( *_a: str , **_a: int )-> Dict:
'''simple docstring'''
return AutoTokenizer.from_pretrained(*_a , **_a )
@add_start_docstrings(AutoModel.__doc__ )
def snake_case ( *_a: List[str] , **_a: Optional[int] )-> Union[str, Any]:
'''simple docstring'''
return AutoModel.from_pretrained(*_a , **_a )
@add_start_docstrings(AutoModelForCausalLM.__doc__ )
def snake_case ( *_a: List[str] , **_a: Tuple )-> Dict:
'''simple docstring'''
return AutoModelForCausalLM.from_pretrained(*_a , **_a )
@add_start_docstrings(AutoModelForMaskedLM.__doc__ )
def snake_case ( *_a: Any , **_a: Optional[int] )-> int:
'''simple docstring'''
return AutoModelForMaskedLM.from_pretrained(*_a , **_a )
@add_start_docstrings(AutoModelForSequenceClassification.__doc__ )
def snake_case ( *_a: Tuple , **_a: int )-> Union[str, Any]:
'''simple docstring'''
return AutoModelForSequenceClassification.from_pretrained(*_a , **_a )
@add_start_docstrings(AutoModelForQuestionAnswering.__doc__ )
def snake_case ( *_a: Union[str, Any] , **_a: List[Any] )-> Any:
'''simple docstring'''
return AutoModelForQuestionAnswering.from_pretrained(*_a , **_a )
| 510 | 1 |
'''simple docstring'''
def UpperCAmelCase_ ( A ):
'''simple docstring'''
_a : Union[str, Any] = 0
while len(a_ ) > 1:
_a : List[Any] = 0
# Consider two files with minimum cost to be merged
for _ in range(2 ):
_a : int = files.index(min(a_ ) )
temp += files[min_index]
files.pop(a_ )
files.append(a_ )
optimal_merge_cost += temp
return optimal_merge_cost
if __name__ == "__main__":
import doctest
doctest.testmod()
| 705 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
UpperCAmelCase_ : List[Any] = {
"google/tapas-base-finetuned-sqa": (
"https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json"
),
"google/tapas-base-finetuned-wtq": (
"https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json"
),
"google/tapas-base-finetuned-wikisql-supervised": (
"https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json"
),
"google/tapas-base-finetuned-tabfact": (
"https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json"
),
}
class a ( snake_case__ ):
'''simple docstring'''
__lowerCAmelCase : Tuple = """tapas"""
def __init__( self , lowerCamelCase_=3_0_5_2_2 , lowerCamelCase_=7_6_8 , lowerCamelCase_=1_2 , lowerCamelCase_=1_2 , lowerCamelCase_=3_0_7_2 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=1_0_2_4 , lowerCamelCase_=[3, 2_5_6, 2_5_6, 2, 2_5_6, 2_5_6, 1_0] , lowerCamelCase_=0.02 , lowerCamelCase_=1e-12 , lowerCamelCase_=0 , lowerCamelCase_=10.0 , lowerCamelCase_=0 , lowerCamelCase_=1.0 , lowerCamelCase_=None , lowerCamelCase_=1.0 , lowerCamelCase_=False , lowerCamelCase_=None , lowerCamelCase_=1.0 , lowerCamelCase_=1.0 , lowerCamelCase_=False , lowerCamelCase_=False , lowerCamelCase_="ratio" , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=6_4 , lowerCamelCase_=3_2 , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=False , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=False , lowerCamelCase_=None , lowerCamelCase_=None , **lowerCamelCase_ , ) -> Optional[Any]:
super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ )
# BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes)
_a : Optional[Any] = vocab_size
_a : List[str] = hidden_size
_a : Union[str, Any] = num_hidden_layers
_a : Tuple = num_attention_heads
_a : Tuple = hidden_act
_a : Optional[Any] = intermediate_size
_a : Dict = hidden_dropout_prob
_a : List[Any] = attention_probs_dropout_prob
_a : int = max_position_embeddings
_a : str = type_vocab_sizes
_a : Tuple = initializer_range
_a : int = layer_norm_eps
# Fine-tuning task hyperparameters
_a : Any = positive_label_weight
_a : Optional[int] = num_aggregation_labels
_a : Any = aggregation_loss_weight
_a : str = use_answer_as_supervision
_a : Optional[int] = answer_loss_importance
_a : int = use_normalized_answer_loss
_a : Optional[int] = huber_loss_delta
_a : Optional[int] = temperature
_a : Union[str, Any] = aggregation_temperature
_a : List[str] = use_gumbel_for_cells
_a : Optional[Any] = use_gumbel_for_aggregation
_a : str = average_approximation_function
_a : Tuple = cell_selection_preference
_a : Tuple = answer_loss_cutoff
_a : Optional[int] = max_num_rows
_a : List[Any] = max_num_columns
_a : Any = average_logits_per_cell
_a : str = select_one_column
_a : Any = allow_empty_column_selection
_a : Dict = init_cell_selection_weights_to_zero
_a : List[Any] = reset_position_index_per_cell
_a : Union[str, Any] = disable_per_token_loss
# Aggregation hyperparameters
_a : Dict = aggregation_labels
_a : List[Any] = no_aggregation_label_index
if isinstance(self.aggregation_labels , lowerCamelCase_ ):
_a : str = {int(lowerCamelCase_ ): v for k, v in aggregation_labels.items()}
| 424 | 0 |
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class UpperCamelCase ( _UpperCAmelCase , unittest.TestCase ):
lowerCAmelCase : Optional[Any] = ShapEImgaImgPipeline
lowerCAmelCase : Dict = ["""image"""]
lowerCAmelCase : List[str] = ["""image"""]
lowerCAmelCase : Tuple = [
"""num_images_per_prompt""",
"""num_inference_steps""",
"""generator""",
"""latents""",
"""guidance_scale""",
"""frame_size""",
"""output_type""",
"""return_dict""",
]
lowerCAmelCase : Optional[int] = False
@property
def __A ( self ):
return 32
@property
def __A ( self ):
return 32
@property
def __A ( self ):
return self.time_input_dim * 4
@property
def __A ( self ):
return 8
@property
def __A ( self ):
torch.manual_seed(0 )
A__ = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , )
A__ = CLIPVisionModel(UpperCAmelCase__ )
return model
@property
def __A ( self ):
A__ = CLIPImageProcessor(
crop_size=224 , do_center_crop=UpperCAmelCase__ , do_normalize=UpperCAmelCase__ , do_resize=UpperCAmelCase__ , image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073] , image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711] , resample=3 , size=224 , )
return image_processor
@property
def __A ( self ):
torch.manual_seed(0 )
A__ = {
"num_attention_heads": 2,
"attention_head_dim": 16,
"embedding_dim": self.time_input_dim,
"num_embeddings": 32,
"embedding_proj_dim": self.text_embedder_hidden_size,
"time_embed_dim": self.time_embed_dim,
"num_layers": 1,
"clip_embed_dim": self.time_input_dim * 2,
"additional_embeddings": 0,
"time_embed_act_fn": "gelu",
"norm_in_type": "layer",
"embedding_proj_norm_type": "layer",
"encoder_hid_proj_type": None,
"added_emb_type": None,
}
A__ = PriorTransformer(**UpperCAmelCase__ )
return model
@property
def __A ( self ):
torch.manual_seed(0 )
A__ = {
"param_shapes": (
(self.renderer_dim, 93),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
"d_latent": self.time_input_dim,
"d_hidden": self.renderer_dim,
"n_output": 12,
"background": (
0.1,
0.1,
0.1,
),
}
A__ = ShapERenderer(**UpperCAmelCase__ )
return model
def __A ( self ):
A__ = self.dummy_prior
A__ = self.dummy_image_encoder
A__ = self.dummy_image_processor
A__ = self.dummy_renderer
A__ = HeunDiscreteScheduler(
beta_schedule="exp" , num_train_timesteps=1_024 , prediction_type="sample" , use_karras_sigmas=UpperCAmelCase__ , clip_sample=UpperCAmelCase__ , clip_sample_range=1.0 , )
A__ = {
"prior": prior,
"image_encoder": image_encoder,
"image_processor": image_processor,
"renderer": renderer,
"scheduler": scheduler,
}
return components
def __A ( self , UpperCAmelCase__ , UpperCAmelCase__=0 ):
A__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ )
if str(UpperCAmelCase__ ).startswith("mps" ):
A__ = torch.manual_seed(UpperCAmelCase__ )
else:
A__ = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ )
A__ = {
"image": input_image,
"generator": generator,
"num_inference_steps": 1,
"frame_size": 32,
"output_type": "np",
}
return inputs
def __A ( self ):
A__ = "cpu"
A__ = self.get_dummy_components()
A__ = self.pipeline_class(**UpperCAmelCase__ )
A__ = pipe.to(UpperCAmelCase__ )
pipe.set_progress_bar_config(disable=UpperCAmelCase__ )
A__ = pipe(**self.get_dummy_inputs(UpperCAmelCase__ ) )
A__ = output.images[0]
A__ = image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
A__ = np.array(
[
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
0.00_039_216,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def __A ( self ):
# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def __A ( self ):
A__ = torch_device == "cpu"
A__ = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=UpperCAmelCase__ , relax_max_difference=UpperCAmelCase__ , )
def __A ( self ):
A__ = self.get_dummy_components()
A__ = self.pipeline_class(**UpperCAmelCase__ )
A__ = pipe.to(UpperCAmelCase__ )
pipe.set_progress_bar_config(disable=UpperCAmelCase__ )
A__ = 1
A__ = 2
A__ = self.get_dummy_inputs(UpperCAmelCase__ )
for key in inputs.keys():
if key in self.batch_params:
A__ = batch_size * [inputs[key]]
A__ = pipe(**UpperCAmelCase__ , num_images_per_prompt=UpperCAmelCase__ )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class UpperCamelCase ( unittest.TestCase ):
def __A ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self ):
A__ = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png" )
A__ = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/shap_e/test_shap_e_img2img_out.npy" )
A__ = ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img" )
A__ = pipe.to(UpperCAmelCase__ )
pipe.set_progress_bar_config(disable=UpperCAmelCase__ )
A__ = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 )
A__ = pipe(
UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="np" , ).images[0]
assert images.shape == (20, 64, 64, 3)
assert_mean_pixel_difference(UpperCAmelCase__ , UpperCAmelCase__ )
| 491 |
import enum
import warnings
from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_tf_available():
import tensorflow as tf
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
UpperCAmelCase_ : Any = logging.get_logger(__name__)
class UpperCamelCase ( enum.Enum ):
lowerCAmelCase : Optional[Any] = 0
lowerCAmelCase : Optional[Any] = 1
@add_end_docstrings(_UpperCAmelCase )
class UpperCamelCase ( _UpperCAmelCase ):
lowerCAmelCase : str = """generated"""
def __init__( self , *UpperCAmelCase__ , **UpperCAmelCase__ ):
super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ )
self.check_model_type(
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
if self.framework == "tf"
else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING )
def __A ( self , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , **UpperCAmelCase__ , ):
A__ = {}
if truncation is not None:
A__ = truncation
A__ = generate_kwargs
A__ = {}
if return_tensors is not None and return_type is None:
A__ = ReturnType.TENSORS if return_tensors else ReturnType.TEXT
if return_type is not None:
A__ = return_type
if clean_up_tokenization_spaces is not None:
A__ = clean_up_tokenization_spaces
if stop_sequence is not None:
A__ = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
if len(UpperCAmelCase__ ) > 1:
warnings.warn(
"Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
" the stop sequence will be used as the stop sequence string in the interim." )
A__ = stop_sequence_ids[0]
return preprocess_params, forward_params, postprocess_params
def __A ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
return True
def __A ( self , *UpperCAmelCase__ , UpperCAmelCase__ ):
A__ = self.model.config.prefix if self.model.config.prefix is not None else ""
if isinstance(args[0] , UpperCAmelCase__ ):
if self.tokenizer.pad_token_id is None:
raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" )
A__ = ([prefix + arg for arg in args[0]],)
A__ = True
elif isinstance(args[0] , UpperCAmelCase__ ):
A__ = (prefix + args[0],)
A__ = False
else:
raise ValueError(
F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" )
A__ = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework )
# This is produced by tokenizers but is an invalid generate kwargs
if "token_type_ids" in inputs:
del inputs["token_type_ids"]
return inputs
def __call__( self , *UpperCAmelCase__ , **UpperCAmelCase__ ):
A__ = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
if (
isinstance(args[0] , UpperCAmelCase__ )
and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] )
and all(len(UpperCAmelCase__ ) == 1 for res in result )
):
return [res[0] for res in result]
return result
def __A ( self , UpperCAmelCase__ , UpperCAmelCase__=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ ):
A__ = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ )
return inputs
def __A ( self , UpperCAmelCase__ , **UpperCAmelCase__ ):
if self.framework == "pt":
A__ , A__ = model_inputs["input_ids"].shape
elif self.framework == "tf":
A__ , A__ = tf.shape(model_inputs["input_ids"] ).numpy()
A__ = generate_kwargs.get("min_length" , self.model.config.min_length )
A__ = generate_kwargs.get("max_length" , self.model.config.max_length )
self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] )
A__ = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ )
A__ = output_ids.shape[0]
if self.framework == "pt":
A__ = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] )
elif self.framework == "tf":
A__ = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) )
return {"output_ids": output_ids}
def __A ( self , UpperCAmelCase__ , UpperCAmelCase__=ReturnType.TEXT , UpperCAmelCase__=False ):
A__ = []
for output_ids in model_outputs["output_ids"][0]:
if return_type == ReturnType.TENSORS:
A__ = {F"""{self.return_name}_token_ids""": output_ids}
elif return_type == ReturnType.TEXT:
A__ = {
F"""{self.return_name}_text""": self.tokenizer.decode(
UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , )
}
records.append(UpperCAmelCase__ )
return records
@add_end_docstrings(_UpperCAmelCase )
class UpperCamelCase ( _UpperCAmelCase ):
lowerCAmelCase : List[str] = """summary"""
def __call__( self , *UpperCAmelCase__ , **UpperCAmelCase__ ):
return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
def __A ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
if max_length < min_length:
logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" )
if input_length < max_length:
logger.warning(
F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """
"a summarization task, where outputs shorter than the input are typically wanted, you might "
F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" )
@add_end_docstrings(_UpperCAmelCase )
class UpperCamelCase ( _UpperCAmelCase ):
lowerCAmelCase : int = """translation"""
def __A ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
if input_length > 0.9 * max_length:
logger.warning(
F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """
"increasing your max_length manually, e.g. translator('...', max_length=400)" )
return True
def __A ( self , *UpperCAmelCase__ , UpperCAmelCase__=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__=None , UpperCAmelCase__=None ):
if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ):
return self.tokenizer._build_translation_inputs(
*UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ )
else:
return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ )
def __A ( self , UpperCAmelCase__=None , UpperCAmelCase__=None , **UpperCAmelCase__ ):
A__ , A__ , A__ = super()._sanitize_parameters(**UpperCAmelCase__ )
if src_lang is not None:
A__ = src_lang
if tgt_lang is not None:
A__ = tgt_lang
if src_lang is None and tgt_lang is None:
# Backward compatibility, direct arguments use is preferred.
A__ = kwargs.get("task" , self.task )
A__ = task.split("_" )
if task and len(UpperCAmelCase__ ) == 4:
# translation, XX, to YY
A__ = items[1]
A__ = items[3]
return preprocess_params, forward_params, postprocess_params
def __call__( self , *UpperCAmelCase__ , **UpperCAmelCase__ ):
return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
| 491 | 1 |
from __future__ import annotations
UpperCAmelCase : int = []
def _SCREAMING_SNAKE_CASE ( a , a , a ) -> bool:
for i in range(len(a ) ):
if board[row][i] == 1:
return False
for i in range(len(a ) ):
if board[i][column] == 1:
return False
for i, j in zip(range(a , -1 , -1 ) , range(a , -1 , -1 ) ):
if board[i][j] == 1:
return False
for i, j in zip(range(a , -1 , -1 ) , range(a , len(a ) ) ):
if board[i][j] == 1:
return False
return True
def _SCREAMING_SNAKE_CASE ( a , a ) -> bool:
if row >= len(a ):
solution.append(a )
printboard(a )
print()
return True
for i in range(len(a ) ):
if is_safe(a , a , a ):
__A : Dict = 1
solve(a , row + 1 )
__A : List[Any] = 0
return False
def _SCREAMING_SNAKE_CASE ( a ) -> None:
for i in range(len(a ) ):
for j in range(len(a ) ):
if board[i][j] == 1:
print('Q' , end=' ' )
else:
print('.' , end=' ' )
print()
# n=int(input("The no. of queens"))
UpperCAmelCase : List[Any] = 8
UpperCAmelCase : Optional[int] = [[0 for i in range(n)] for j in range(n)]
solve(board, 0)
print('''The total no. of solutions are :''', len(solution))
| 77 |
from collections import OrderedDict
from typing import Any, List, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging
UpperCAmelCase : Dict = logging.get_logger(__name__)
UpperCAmelCase : str = {
'''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''',
'''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''',
'''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''',
'''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''',
'''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''',
'''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''',
'''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''',
'''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''',
'''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''',
'''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''',
'''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''',
'''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''',
}
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : List[str] = '''codegen'''
UpperCamelCase : List[str] = {
'''max_position_embeddings''': '''n_positions''',
'''hidden_size''': '''n_embd''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ):
__A : Any = vocab_size
__A : Tuple = n_ctx
__A : Union[str, Any] = n_positions
__A : Optional[Any] = n_embd
__A : Any = n_layer
__A : Dict = n_head
__A : Union[str, Any] = n_inner
__A : List[Any] = rotary_dim
__A : str = activation_function
__A : Any = resid_pdrop
__A : Tuple = embd_pdrop
__A : Tuple = attn_pdrop
__A : Union[str, Any] = layer_norm_epsilon
__A : str = initializer_range
__A : Optional[Any] = use_cache
__A : Union[str, Any] = bos_token_id
__A : Tuple = eos_token_id
super().__init__(
bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A )
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A = "default" , _A = None , _A = False , ):
super().__init__(_A , task=_A , patching_specs=_A , use_past=_A )
if not getattr(self._config , 'pad_token_id' , _A ):
# TODO: how to do that better?
__A : Dict = 0
@property
def UpperCAmelCase_ ( self ):
__A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} )
if self.use_past:
self.fill_with_past_key_values_(_A , direction='inputs' )
__A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'}
else:
__A : int = {0: 'batch', 1: 'sequence'}
return common_inputs
@property
def UpperCAmelCase_ ( self ):
return self._config.n_layer
@property
def UpperCAmelCase_ ( self ):
return self._config.n_head
def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ):
__A : Any = super(_A , self ).generate_dummy_inputs(
_A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A )
# We need to order the input in the way they appears in the forward()
__A : str = OrderedDict({'input_ids': common_inputs['input_ids']} )
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' )
else:
import torch
__A , __A : Any = common_inputs['input_ids'].shape
# Not using the same length for past_key_values
__A : Any = seqlen + 2
__A : List[str] = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
__A : Optional[Any] = [
(torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers )
]
__A : Tuple = common_inputs['attention_mask']
if self.use_past:
__A : str = ordered_inputs['attention_mask'].dtype
__A : List[Any] = torch.cat(
[ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 )
return ordered_inputs
@property
def UpperCAmelCase_ ( self ):
return 13
| 77 | 1 |
'''simple docstring'''
import argparse
import importlib
from pathlib import Path
# Test all the extensions added in the setup
UpperCamelCase : int = [
'kernels/rwkv/wkv_cuda.cu',
'kernels/rwkv/wkv_op.cpp',
'kernels/deformable_detr/ms_deform_attn.h',
'kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh',
'models/graphormer/algos_graphormer.pyx',
]
def A__ ( __lowerCAmelCase : Union[str, Any] ):
# Test all the extensions added in the setup
for file in FILES_TO_FIND:
if not (transformers_path / file).exists():
return False
return True
if __name__ == "__main__":
UpperCamelCase : Dict = argparse.ArgumentParser()
parser.add_argument('--check_lib', action='store_true', help='Whether to check the build or the actual package.')
UpperCamelCase : Union[str, Any] = parser.parse_args()
if args.check_lib:
UpperCamelCase : Optional[int] = importlib.import_module('transformers')
UpperCamelCase : int = Path(transformers_module.__file__).parent
else:
UpperCamelCase : List[str] = Path.cwd() / 'build/lib/transformers'
if not test_custom_files_are_present(transformers_path):
raise ValueError('The built release does not contain the custom files. Fix this before going further!')
| 50 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCamelCase : Tuple = {
'configuration_mvp': ['MVP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MvpConfig', 'MvpOnnxConfig'],
'tokenization_mvp': ['MvpTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : str = ['MvpTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase : Optional[int] = [
'MVP_PRETRAINED_MODEL_ARCHIVE_LIST',
'MvpForCausalLM',
'MvpForConditionalGeneration',
'MvpForQuestionAnswering',
'MvpForSequenceClassification',
'MvpModel',
'MvpPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
UpperCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 50 | 1 |
from math import factorial
def _a ( lowercase__ : int = 1_00 ):
'''simple docstring'''
return sum(map(lowercase__ , str(factorial(lowercase__ ) ) ) )
if __name__ == "__main__":
print(solution(int(input("Enter the Number: ").strip())))
| 702 | import heapq as hq
import math
from collections.abc import Iterator
class snake_case :
def __init__( self : str , a_ : str )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : List[str] = str(id_ )
SCREAMING_SNAKE_CASE__ : Any = None
SCREAMING_SNAKE_CASE__ : Optional[Any] = None
SCREAMING_SNAKE_CASE__ : Any = []
SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance}
def __lt__( self : int , a_ : Tuple )-> Union[str, Any]:
"""simple docstring"""
return self.key < other.key
def __repr__( self : Any )-> Dict:
"""simple docstring"""
return self.id
def __lowercase( self : Optional[Any] , a_ : int )-> List[str]:
"""simple docstring"""
self.neighbors.append(a_ )
def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ : Tuple = weight
def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ):
'''simple docstring'''
graph[a - 1].add_neighbor(graph[b - 1] )
graph[b - 1].add_neighbor(graph[a - 1] )
# add the edges:
graph[a - 1].add_edge(graph[b - 1] , lowercase__ )
graph[b - 1].add_edge(graph[a - 1] , lowercase__ )
def _a ( lowercase__ : list , lowercase__ : Vertex ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Any = []
for u in graph:
SCREAMING_SNAKE_CASE__ : Dict = math.inf
SCREAMING_SNAKE_CASE__ : str = None
SCREAMING_SNAKE_CASE__ : List[str] = 0
SCREAMING_SNAKE_CASE__ : int = graph[:]
while q:
SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ )
q.remove(lowercase__ )
for v in u.neighbors:
if (v in q) and (u.edges[v.id] < v.key):
SCREAMING_SNAKE_CASE__ : int = u
SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id]
for i in range(1 , len(lowercase__ ) ):
a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) )
return a
def _a ( lowercase__ : list , lowercase__ : Vertex ):
'''simple docstring'''
for u in graph:
SCREAMING_SNAKE_CASE__ : List[str] = math.inf
SCREAMING_SNAKE_CASE__ : int = None
SCREAMING_SNAKE_CASE__ : Optional[Any] = 0
SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ )
hq.heapify(lowercase__ )
while h:
SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ )
for v in u.neighbors:
if (v in h) and (u.edges[v.id] < v.key):
SCREAMING_SNAKE_CASE__ : List[str] = u
SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id]
hq.heapify(lowercase__ )
for i in range(1 , len(lowercase__ ) ):
yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1)
def _a ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 636 | 0 |
'''simple docstring'''
import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple
import numpy as np
from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_: List[Any] ={'vocab_file': 'vocab.txt', 'emoji_file': 'emoji.json'}
SCREAMING_SNAKE_CASE_: List[Any] ={
'vocab_file': {
'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt',
},
'emoji_file': {
'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json',
},
}
SCREAMING_SNAKE_CASE_: Optional[Any] ={
'abeja/gpt-neox-japanese-2.7b': 20_48,
}
def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Tuple ) -> int:
'''simple docstring'''
with open(snake_case_ , "r" , encoding="utf-8" ) as f:
UpperCAmelCase_ = json.loads(f.read() )
UpperCAmelCase_ = collections.OrderedDict()
UpperCAmelCase_ = collections.OrderedDict()
UpperCAmelCase_ = collections.OrderedDict()
with open(snake_case_ , "r" , encoding="utf-8" ) as f:
UpperCAmelCase_ = f.readlines()
UpperCAmelCase_ = [[t.rstrip("\n" )] if (t == "," or "," not in t) else t.rstrip("\n" ).split("," ) for t in token]
for idx, b in enumerate(snake_case_ ):
UpperCAmelCase_ = b
UpperCAmelCase_ = idx
for wd in b:
UpperCAmelCase_ = idx
return vocab, raw_vocab, ids_to_tokens, emoji
class __A ( UpperCamelCase__ ):
a__ : int = VOCAB_FILES_NAMES
a__ : List[Any] = PRETRAINED_VOCAB_FILES_MAP
a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a__ : Tuple = ["""input_ids""", """attention_mask"""]
def __init__(self : int , __a : Any , __a : int , __a : Optional[Any]="<|endoftext|>" , __a : Optional[Any]="<|endoftext|>" , __a : Optional[Any]="<|startoftext|>" , __a : int="<|endoftext|>" , __a : Tuple=False , **__a : Tuple , ):
super().__init__(
unk_token=__a , pad_token=__a , bos_token=__a , eos_token=__a , do_clean_text=__a , **__a , )
if not os.path.isfile(__a ):
raise ValueError(
f"""Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"""
" model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" )
if not os.path.isfile(__a ):
raise ValueError(
f"""Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"""
" pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" )
UpperCAmelCase_ = do_clean_text
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = load_vocab_and_emoji(__a , __a )
UpperCAmelCase_ = SubWordJapaneseTokenizer(
vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji )
@property
def _lowercase (self : int ):
# self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
return len(self.raw_vocab )
def _lowercase (self : Union[str, Any] ):
return dict(self.raw_vocab , **self.added_tokens_encoder )
def _lowercase (self : Optional[int] , __a : List[str] ):
return self.subword_tokenizer.tokenize(__a , clean=self.do_clean_text )
def _lowercase (self : Any , __a : List[Any] ):
return self.vocab.get(__a , self.vocab.get(self.unk_token ) )
def _lowercase (self : Tuple , __a : Tuple ):
return self.subword_tokenizer.convert_id_to_token(__a )
def _lowercase (self : Optional[Any] , __a : Optional[int] ):
UpperCAmelCase_ = "".join(__a ).strip()
return out_string
def _lowercase (self : Any , __a : "Conversation" ):
UpperCAmelCase_ = []
for is_user, text in conversation.iter_texts():
input_ids.extend(self.encode(__a , add_special_tokens=__a ) + [self.eos_token_id] )
if len(__a ) > self.model_max_length:
UpperCAmelCase_ = input_ids[-self.model_max_length :]
return input_ids
def _lowercase (self : Optional[Any] , __a : str , __a : Optional[str] = None ):
UpperCAmelCase_ = 0
if os.path.isdir(__a ):
UpperCAmelCase_ = os.path.join(
__a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
UpperCAmelCase_ = os.path.join(
__a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"] )
else:
UpperCAmelCase_ = (
(filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
)
UpperCAmelCase_ = (
(filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
)
with open(__a , "w" , encoding="utf-8" ) as writer:
for token_index, token in self.ids_to_tokens.items():
if index != token_index:
logger.warning(
f"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."""
" Please check that the vocabulary is not corrupted!" )
UpperCAmelCase_ = token_index
writer.write(",".join(__a ) + "\n" )
index += 1
with open(__a , "w" , encoding="utf-8" ) as writer:
json.dump(self.emoji , __a )
return vocab_file, emoji_file
class __A ( UpperCamelCase__ ):
def __init__(self : Optional[Any] , __a : str , __a : Tuple , __a : Optional[int] ):
UpperCAmelCase_ = vocab # same as swe
UpperCAmelCase_ = ids_to_tokens # same as bpe
UpperCAmelCase_ = emoji
UpperCAmelCase_ = np.max([len(__a ) for w in self.vocab.keys()] )
UpperCAmelCase_ = re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)" )
UpperCAmelCase_ = re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*" )
UpperCAmelCase_ = re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}" )
UpperCAmelCase_ = re.compile(
r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" )
UpperCAmelCase_ = re.compile(
r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" )
UpperCAmelCase_ = re.compile(
r"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*" )
UpperCAmelCase_ = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
UpperCAmelCase_ = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
UpperCAmelCase_ = str.maketrans({k: "<BLOCK>" for k in keisen + blocks} )
def __len__(self : Dict ):
return len(self.ids_to_tokens )
def _lowercase (self : Union[str, Any] , __a : Optional[int] ):
UpperCAmelCase_ = self.content_repattera.sub("<URL>" , __a )
UpperCAmelCase_ = self.content_repattera.sub("<EMAIL>" , __a )
UpperCAmelCase_ = self.content_repattera.sub("<TEL>" , __a )
UpperCAmelCase_ = self.content_repattera.sub("<DATE>" , __a )
UpperCAmelCase_ = self.content_repattera.sub("<DATE>" , __a )
UpperCAmelCase_ = self.content_repattera.sub("<PRICE>" , __a )
UpperCAmelCase_ = content.translate(self.content_transa )
while "<BLOCK><BLOCK>" in content:
UpperCAmelCase_ = content.replace("<BLOCK><BLOCK>" , "<BLOCK>" )
return content
def _lowercase (self : List[str] , __a : Union[str, Any] , __a : str=False ):
UpperCAmelCase_ = text.replace(" " , "<SP>" )
UpperCAmelCase_ = text.replace(" " , "<SP>" )
UpperCAmelCase_ = text.replace("\r\n" , "<BR>" )
UpperCAmelCase_ = text.replace("\n" , "<BR>" )
UpperCAmelCase_ = text.replace("\r" , "<BR>" )
UpperCAmelCase_ = text.replace("\t" , "<TAB>" )
UpperCAmelCase_ = text.replace("—" , "ー" )
UpperCAmelCase_ = text.replace("−" , "ー" )
for k, v in self.emoji["emoji"].items():
if k in text:
UpperCAmelCase_ = text.replace(__a , __a )
if clean:
UpperCAmelCase_ = self.clean_text(__a )
def check_simbol(__a : Union[str, Any] ):
UpperCAmelCase_ = x.encode()
if len(__a ) == 1 and len(__a ) == 2:
UpperCAmelCase_ = (int(e[0] ) << 8) + int(e[1] )
if (
(c >= 0Xc2_a1 and c <= 0Xc2_bf)
or (c >= 0Xc7_80 and c <= 0Xc7_83)
or (c >= 0Xca_b9 and c <= 0Xcb_bf)
or (c >= 0Xcc_80 and c <= 0Xcd_a2)
):
return True
return False
def checkuae(__a : Dict ):
UpperCAmelCase_ = x.encode()
if len(__a ) == 1 and len(__a ) == 3:
UpperCAmelCase_ = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] )
if c >= 0Xe2_80_80 and c <= 0Xe2_b0_7f:
return True
return False
UpperCAmelCase_ = 0
UpperCAmelCase_ = []
while pos < len(__a ):
UpperCAmelCase_ = min(len(__a ) , pos + self.maxlen + 1 ) if text[pos] == "<" else pos + 3
UpperCAmelCase_ = [] # (token_id, token, pos)
for e in range(__a , __a , -1 ):
UpperCAmelCase_ = text[pos:e]
if wd in self.vocab:
if wd[0] == "<" and len(__a ) > 2:
UpperCAmelCase_ = [(self.vocab[wd], wd, e)]
break
else:
candidates.append((self.vocab[wd], wd, e) )
if len(__a ) > 0:
# the smallest token_id is adopted
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = sorted(__a , key=lambda __a : x[0] )[0]
result.append(__a )
UpperCAmelCase_ = e
else:
UpperCAmelCase_ = pos + 1
UpperCAmelCase_ = text[pos:end]
if check_simbol(__a ):
result.append("<KIGOU>" )
elif checkuae(__a ):
result.append("<U2000U2BFF>" )
else:
for i in wd.encode("utf-8" ):
result.append("<|byte%d|>" % i )
UpperCAmelCase_ = end
return result
def _lowercase (self : Dict , __a : Tuple , __a : Optional[Any]="\n" ):
UpperCAmelCase_ = []
UpperCAmelCase_ = []
UpperCAmelCase_ = self.ids_to_tokens[index][0]
if word[:6] == "<|byte" and word[-2:] == "|>":
byte_tokens.append(int(word[6:-2] ) )
else:
if len(__a ) > 0:
words.append(bytearray(__a ).decode("utf-8" , errors="replace" ) )
UpperCAmelCase_ = []
if word[:7] == "<|emoji" and word[-2:] == "|>":
words.append(self.emoji["emoji_inv"][word] )
elif word == "<SP>":
words.append(" " )
elif word == "<BR>":
words.append(__a )
elif word == "<TAB>":
words.append("\t" )
elif word == "<BLOCK>":
words.append("▀" )
elif word == "<KIGOU>":
words.append("ǀ" )
elif word == "<U2000U2BFF>":
words.append("‖" )
else:
words.append(__a )
if len(__a ) > 0:
words.append(bytearray(__a ).decode("utf-8" , errors="replace" ) )
UpperCAmelCase_ = "".join(__a )
return text
| 78 | '''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.
from typing import TYPE_CHECKING
from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool
if TYPE_CHECKING:
from PIL import Image
class __A ( UpperCamelCase__ ):
a__ : List[str] = """Salesforce/blip-image-captioning-base"""
a__ : Optional[Any] = (
"""This is a tool that generates a description of an image. It takes an input named `image` which should be the """
"""image to caption, and returns a text that contains the description in English."""
)
a__ : str = """image_captioner"""
a__ : List[str] = AutoModelForVisionaSeq
a__ : int = ["""image"""]
a__ : Optional[Any] = ["""text"""]
def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ):
requires_backends(self , ["vision"] )
super().__init__(*__a , **__a )
def _lowercase (self : Union[str, Any] , __a : "Image" ):
return self.pre_processor(images=__a , return_tensors="pt" )
def _lowercase (self : List[str] , __a : Dict ):
return self.model.generate(**__a )
def _lowercase (self : int , __a : Optional[Any] ):
return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
| 78 | 1 |
"""simple docstring"""
import tempfile
import unittest
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.testing_utils import (
is_torch_available,
require_optimum,
require_torch,
slow,
)
if is_torch_available():
import torch
@require_torch
@require_optimum
@slow
class lowercase_ ( unittest.TestCase ):
'''simple docstring'''
def lowerCAmelCase_ ( self : Optional[Any] ):
_A = 'hf-internal-testing/tiny-random-t5'
_A = AutoTokenizer.from_pretrained(_UpperCAmelCase )
_A = AutoModelForSeqaSeqLM.from_pretrained(_UpperCAmelCase )
_A = tokenizer('This is me' , return_tensors='pt' )
_A = model.to_bettertransformer()
self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) )
_A = model.generate(**_UpperCAmelCase )
_A = model.reverse_bettertransformer()
self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(_UpperCAmelCase )
_A = AutoModelForSeqaSeqLM.from_pretrained(_UpperCAmelCase )
self.assertFalse(
any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) )
_A = model_reloaded.generate(**_UpperCAmelCase )
self.assertTrue(torch.allclose(_UpperCAmelCase , _UpperCAmelCase ) )
def lowerCAmelCase_ ( self : int ):
_A = 'hf-internal-testing/tiny-random-t5'
_A = AutoModelForSeqaSeqLM.from_pretrained(_UpperCAmelCase )
_A = model.to_bettertransformer()
with tempfile.TemporaryDirectory() as tmpdirname:
with self.assertRaises(_UpperCAmelCase ):
model.save_pretrained(_UpperCAmelCase )
_A = model.reverse_bettertransformer()
model.save_pretrained(_UpperCAmelCase )
| 711 |
"""simple docstring"""
a = 256
# Modulus to hash a string
a = 1_000_003
def _snake_case ( _snake_case : str , _snake_case : str ) -> bool:
'''simple docstring'''
_A = len(_snake_case )
_A = len(_snake_case )
if p_len > t_len:
return False
_A = 0
_A = 0
_A = 1
# Calculating the hash of pattern and substring of text
for i in range(_snake_case ):
_A = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus
_A = (ord(text[i] ) + text_hash * alphabet_size) % modulus
if i == p_len - 1:
continue
_A = (modulus_power * alphabet_size) % modulus
for i in range(0 , t_len - p_len + 1 ):
if text_hash == p_hash and text[i : i + p_len] == pattern:
return True
if i == t_len - p_len:
continue
# Calculate the https://en.wikipedia.org/wiki/Rolling_hash
_A = (
(text_hash - ord(text[i] ) * modulus_power) * alphabet_size
+ ord(text[i + p_len] )
) % modulus
return False
def _snake_case ( ) -> None:
'''simple docstring'''
_A = 'abc1abc12'
_A = 'alskfjaldsabc1abc1abc12k23adsfabcabc'
_A = 'alskfjaldsk23adsfabcabc'
assert rabin_karp(_snake_case , _snake_case ) and not rabin_karp(_snake_case , _snake_case )
# Test 2)
_A = 'ABABX'
_A = 'ABABZABABYABABX'
assert rabin_karp(_snake_case , _snake_case )
# Test 3)
_A = 'AAAB'
_A = 'ABAAAAAB'
assert rabin_karp(_snake_case , _snake_case )
# Test 4)
_A = 'abcdabcy'
_A = 'abcxabcdabxabcdabcdabcy'
assert rabin_karp(_snake_case , _snake_case )
# Test 5)
_A = 'Lü'
_A = 'Lüsai'
assert rabin_karp(_snake_case , _snake_case )
_A = 'Lue'
assert not rabin_karp(_snake_case , _snake_case )
print('Success.' )
if __name__ == "__main__":
test_rabin_karp()
| 505 | 0 |
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str ):
SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ )
SCREAMING_SNAKE_CASE__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )]
SCREAMING_SNAKE_CASE__ = True
for i in range(UpperCamelCase__ ):
for j in range(m + 1 ):
if dp[i][j]:
if j < m and a[i].upper() == b[j]:
SCREAMING_SNAKE_CASE__ = True
if a[i].islower():
SCREAMING_SNAKE_CASE__ = True
return dp[n][m]
if __name__ == "__main__":
import doctest
doctest.testmod() | 6 |
"""simple docstring"""
from __future__ import annotations
from fractions import Fraction
def UpperCAmelCase ( snake_case : int , snake_case : int ):
return (
num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
)
def UpperCAmelCase ( snake_case : int ):
_lowerCAmelCase:Optional[Any] = []
_lowerCAmelCase:Dict = 11
_lowerCAmelCase:int = int('''1''' + '''0''' * digit_len )
for num in range(snake_case , snake_case ):
while den <= 99:
if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
if is_digit_cancelling(snake_case , snake_case ):
solutions.append(F'{num}/{den}' )
den += 1
num += 1
_lowerCAmelCase:Optional[Any] = 10
return solutions
def UpperCAmelCase ( snake_case : int = 2 ):
_lowerCAmelCase:Optional[int] = 1.0
for fraction in fraction_list(snake_case ):
_lowerCAmelCase:Any = Fraction(snake_case )
result *= frac.denominator / frac.numerator
return int(snake_case )
if __name__ == "__main__":
print(solution())
| 227 | 0 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from ..utils import cached_file
# docstyle-ignore
a_ :Optional[int] = "\nHuman: <<task>>\n\nAssistant: "
a_ :List[str] = "huggingface-tools/default-prompts"
a_ :List[str] = {"chat": "chat_prompt_template.txt", "run": "run_prompt_template.txt"}
def lowercase_ (A : Union[str, Any] , A : Optional[int] , A : Optional[Any]="run" ):
if prompt_or_repo_id is None:
snake_case__ : Optional[Any] = DEFAULT_PROMPTS_REPO
# prompt is considered a repo ID when it does not contain any kind of space
if re.search('\\s' , A ) is not None:
return prompt_or_repo_id
snake_case__ : Dict = cached_file(
A , PROMPT_FILES[mode] , repo_type='dataset' , user_agent={'agent': agent_name} )
with open(A , 'r' , encoding='utf-8' ) as f:
return f.read()
| 703 |
import math
def lowercase_ (A : int ):
if not isinstance(A , A ):
snake_case__ : List[Any] = F'''Input value of [number={number}] must be an integer'''
raise TypeError(A )
if number < 1:
snake_case__ : List[Any] = F'''Input value of [number={number}] must be > 0'''
raise ValueError(A )
elif number == 1:
return 3
elif number == 2:
return 5
else:
snake_case__ : Optional[Any] = int(math.log(number // 3 , 2 ) ) + 2
snake_case__ : Tuple = [3, 5]
snake_case__ : List[str] = 2
snake_case__ : Optional[int] = 3
for block in range(1 , A ):
for _ in range(A ):
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] )
proth_index += 1
increment *= 2
return proth_list[number - 1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for number in range(11):
a_ :str = 0
try:
a_ :List[Any] = proth(number)
except ValueError:
print(F"""ValueError: there is no {number}th Proth number""")
continue
print(F"""The {number}th Proth number: {value}""")
| 243 | 0 |
def snake_case ( snake_case__ :Any) -> List[Any]:
if length <= 0 or not isinstance(a__ , a__):
raise ValueError("""Length must be a positive integer.""")
return [n * (2 * n - 1) for n in range(a__)]
if __name__ == "__main__":
print(hexagonal_numbers(length=5))
print(hexagonal_numbers(length=10))
| 401 |
'''simple docstring'''
import math
def a__ ( a__ ):
"""simple docstring"""
return math.sqrt(a__ ) * math.sqrt(a__ ) == num
def a__ ( a__ ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = n
while left <= right:
__SCREAMING_SNAKE_CASE = (left + right) // 2
if mid**2 == n:
return True
elif mid**2 > n:
__SCREAMING_SNAKE_CASE = mid - 1
else:
__SCREAMING_SNAKE_CASE = mid + 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 627 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCAmelCase__ : Optional[Any] ={
'''configuration_x_clip''': [
'''XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''XCLIPConfig''',
'''XCLIPTextConfig''',
'''XCLIPVisionConfig''',
],
'''processing_x_clip''': ['''XCLIPProcessor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ : List[Any] =[
'''XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''XCLIPModel''',
'''XCLIPPreTrainedModel''',
'''XCLIPTextModel''',
'''XCLIPVisionModel''',
]
if TYPE_CHECKING:
from .configuration_x_clip import (
XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
XCLIPConfig,
XCLIPTextConfig,
XCLIPVisionConfig,
)
from .processing_x_clip import XCLIPProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_x_clip import (
XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
XCLIPModel,
XCLIPPreTrainedModel,
XCLIPTextModel,
XCLIPVisionModel,
)
else:
import sys
UpperCAmelCase__ : int =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 269 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
UpperCAmelCase__ : List[Any] ={'''configuration_yolos''': ['''YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''YolosConfig''', '''YolosOnnxConfig''']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ : Dict =['''YolosFeatureExtractor''']
UpperCAmelCase__ : List[Any] =['''YolosImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ : Optional[Any] =[
'''YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''YolosForObjectDetection''',
'''YolosModel''',
'''YolosPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_yolos import YolosFeatureExtractor
from .image_processing_yolos import YolosImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_yolos import (
YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST,
YolosForObjectDetection,
YolosModel,
YolosPreTrainedModel,
)
else:
import sys
UpperCAmelCase__ : Optional[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 269 | 1 |
"""simple docstring"""
import inspect
import unittest
from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MobileNetVaForImageClassification, MobileNetVaModel
from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import MobileNetVaImageProcessor
class lowerCAmelCase_ ( _lowercase ):
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]:
A = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(A_ ,'tf_padding' ) )
self.parent.assertTrue(hasattr(A_ ,'depth_multiplier' ) )
class lowerCAmelCase_ :
'''simple docstring'''
def __init__( self : List[Any] ,A_ : Optional[int] ,A_ : Optional[int]=13 ,A_ : Tuple=3 ,A_ : Any=32 ,A_ : Optional[Any]=0.25 ,A_ : Union[str, Any]=8 ,A_ : List[str]=True ,A_ : List[Any]=1024 ,A_ : str=32 ,A_ : Tuple="relu6" ,A_ : Optional[int]=0.1 ,A_ : int=0.02 ,A_ : int=True ,A_ : Any=True ,A_ : Optional[int]=10 ,A_ : List[Any]=None ,) -> List[Any]:
A = parent
A = batch_size
A = num_channels
A = image_size
A = depth_multiplier
A = min_depth
A = tf_padding
A = int(last_hidden_size * depth_multiplier )
A = output_stride
A = hidden_act
A = classifier_dropout_prob
A = use_labels
A = is_training
A = num_labels
A = initializer_range
A = scope
def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any:
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 _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]:
return MobileNetVaConfig(
num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,)
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : int ,A_ : List[Any] ,A_ : Optional[Any] ,A_ : Tuple ) -> List[Any]:
A = MobileNetVaModel(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 _SCREAMING_SNAKE_CASE ( self : Any ,A_ : int ,A_ : Dict ,A_ : Optional[Any] ,A_ : Union[str, Any] ) -> Tuple:
A = self.num_labels
A = MobileNetVaForImageClassification(A_ )
model.to(A_ )
model.eval()
A = model(A_ ,labels=A_ )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]:
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 lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ):
'''simple docstring'''
_lowerCamelCase: List[str] = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
_lowerCamelCase: Any = (
{'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
if is_torch_available()
else {}
)
_lowerCamelCase: List[str] = False
_lowerCamelCase: Optional[Any] = False
_lowerCamelCase: List[Any] = False
_lowerCamelCase: Union[str, Any] = False
def _SCREAMING_SNAKE_CASE ( self : Any ) -> str:
A = MobileNetVaModelTester(self )
A = MobileNetVaConfigTester(self ,config_class=A_ ,has_text_modality=A_ )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple:
self.config_tester.run_common_tests()
@unittest.skip(reason='MobileNetV1 does not use inputs_embeds' )
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]:
pass
@unittest.skip(reason='MobileNetV1 does not support input and output embeddings' )
def _SCREAMING_SNAKE_CASE ( self : int ) -> Union[str, Any]:
pass
@unittest.skip(reason='MobileNetV1 does not output attentions' )
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]:
pass
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]:
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_ )
def _SCREAMING_SNAKE_CASE ( self : str ) -> Tuple:
A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*A_ )
def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]:
def check_hidden_states_output(A_ : int ,A_ : Dict ,A_ : str ):
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 = 26
self.assertEqual(len(A_ ) ,A_ )
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 _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]:
A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*A_ )
@slow
def _SCREAMING_SNAKE_CASE ( self : str ) -> int:
for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A = MobileNetVaModel.from_pretrained(A_ )
self.assertIsNotNone(A_ )
def _snake_case ( ):
A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class lowerCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict:
return (
MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224' ) if is_vision_available() else None
)
@slow
def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str:
A = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224' ).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, 1001) )
self.assertEqual(outputs.logits.shape ,A_ )
A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A_ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A_ ,atol=1e-4 ) ) | 91 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
A_ = {
"configuration_ctrl": ["CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP", "CTRLConfig"],
"tokenization_ctrl": ["CTRLTokenizer"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A_ = [
"CTRL_PRETRAINED_MODEL_ARCHIVE_LIST",
"CTRLForSequenceClassification",
"CTRLLMHeadModel",
"CTRLModel",
"CTRLPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A_ = [
"TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFCTRLForSequenceClassification",
"TFCTRLLMHeadModel",
"TFCTRLModel",
"TFCTRLPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig
from .tokenization_ctrl import CTRLTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ctrl import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
CTRLPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_ctrl import (
TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFCTRLForSequenceClassification,
TFCTRLLMHeadModel,
TFCTRLModel,
TFCTRLPreTrainedModel,
)
else:
import sys
A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 391 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( _lowerCamelCase : str , _lowerCamelCase : str ) -> int:
if len(_lowerCamelCase ) != len(_lowerCamelCase ):
raise ValueError('String lengths must match!' )
lowerCamelCase_ = 0
for chara, chara in zip(_lowerCamelCase , _lowerCamelCase ):
if chara != chara:
count += 1
return count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 137 |
"""simple docstring"""
import numpy as np
class a :
def __init__( self : int ) -> Optional[Any]:
lowerCamelCase_ = (0, 0)
lowerCamelCase_ = None
lowerCamelCase_ = 0
lowerCamelCase_ = 0
lowerCamelCase_ = 0
def __eq__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any ) -> Tuple:
return self.position == cell.position
def UpperCamelCase ( self : List[Any] ) -> List[Any]:
print(self.position )
class a :
def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : List[str]=(5, 5) ) -> Any:
lowerCamelCase_ = np.zeros(__SCREAMING_SNAKE_CASE )
lowerCamelCase_ = world_size[0]
lowerCamelCase_ = world_size[1]
def UpperCamelCase ( self : str ) -> Optional[int]:
print(self.w )
def UpperCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[int] ) -> Optional[int]:
lowerCamelCase_ = [
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
]
lowerCamelCase_ = cell.position[0]
lowerCamelCase_ = cell.position[1]
lowerCamelCase_ = []
for n in neughbour_cord:
lowerCamelCase_ = current_x + n[0]
lowerCamelCase_ = current_y + n[1]
if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit:
lowerCamelCase_ = Cell()
lowerCamelCase_ = (x, y)
lowerCamelCase_ = cell
neighbours.append(__SCREAMING_SNAKE_CASE )
return neighbours
def lowerCamelCase__ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : List[Any] , _lowerCamelCase : Dict ) -> Optional[Any]:
lowerCamelCase_ = []
lowerCamelCase_ = []
_open.append(_lowerCamelCase )
while _open:
lowerCamelCase_ = np.argmin([n.f for n in _open] )
lowerCamelCase_ = _open[min_f]
_closed.append(_open.pop(_lowerCamelCase ) )
if current == goal:
break
for n in world.get_neigbours(_lowerCamelCase ):
for c in _closed:
if c == n:
continue
lowerCamelCase_ = current.g + 1
lowerCamelCase_ , lowerCamelCase_ = n.position
lowerCamelCase_ , lowerCamelCase_ = goal.position
lowerCamelCase_ = (ya - ya) ** 2 + (xa - xa) ** 2
lowerCamelCase_ = n.h + n.g
for c in _open:
if c == n and c.f < n.f:
continue
_open.append(_lowerCamelCase )
lowerCamelCase_ = []
while current.parent is not None:
path.append(current.position )
lowerCamelCase_ = current.parent
path.append(current.position )
return path[::-1]
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE : Optional[Any] = Gridworld()
# Start position and goal
_SCREAMING_SNAKE_CASE : Tuple = Cell()
_SCREAMING_SNAKE_CASE : Union[str, Any] = (0, 0)
_SCREAMING_SNAKE_CASE : Optional[Any] = Cell()
_SCREAMING_SNAKE_CASE : Optional[int] = (4, 4)
print(F'''path from {start.position} to {goal.position}''')
_SCREAMING_SNAKE_CASE : Tuple = astar(world, start, goal)
# Just for visual reasons.
for i in s:
_SCREAMING_SNAKE_CASE : str = 1
print(world.w)
| 137 | 1 |
'''simple docstring'''
import requests
_snake_case : Union[str, Any] = 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey='
def snake_case_ (UpperCamelCase : str ):
'''simple docstring'''
_a = requests.get(_NEWS_API + bbc_news_api_key ).json()
# each article in the list is a dict
for i, article in enumerate(bbc_news_page['''articles'''] , 1 ):
print(f'{i}.) {article["title"]}' )
if __name__ == "__main__":
fetch_bbc_news(bbc_news_api_key='<Your BBC News API key goes here>')
| 22 |
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__ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] , snake_case_ : Union[str, Any]=[] ) -> Union[str, Any]:
__snake_case = size[0] - overlap_pixels * 2
__snake_case = 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
__snake_case = np.ones((size_y, size_x) , dtype=np.uinta ) * 255
__snake_case = np.pad(snake_case_ , mode='''linear_ramp''' , pad_width=snake_case_ , end_values=0 )
if "l" in remove_borders:
__snake_case = mask[:, overlap_pixels : mask.shape[1]]
if "r" in remove_borders:
__snake_case = mask[:, 0 : mask.shape[1] - overlap_pixels]
if "t" in remove_borders:
__snake_case = mask[overlap_pixels : mask.shape[0], :]
if "b" in remove_borders:
__snake_case = mask[0 : mask.shape[0] - overlap_pixels, :]
return mask
def lowerCamelCase__ ( snake_case_ : List[Any] , snake_case_ : Tuple , snake_case_ : Optional[Any] ) -> str:
return max(snake_case_ , min(snake_case_ , snake_case_ ) )
def lowerCamelCase__ ( snake_case_ : [int] , snake_case_ : [int] , snake_case_ : [int] ) -> Optional[Any]:
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__ ( snake_case_ : [int] , snake_case_ : int , snake_case_ : [int] ) -> Tuple:
__snake_case = list(snake_case_ )
rect[0] -= overlap
rect[1] -= overlap
rect[2] += overlap
rect[3] += overlap
__snake_case = clamp_rect(snake_case_ , [0, 0] , [image_size[0], image_size[1]] )
return rect
def lowerCamelCase__ ( snake_case_ : Union[str, Any] , snake_case_ : Optional[int] , snake_case_ : Optional[Any] , snake_case_ : List[str] ) -> str:
__snake_case = 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(snake_case_ , (original_slice, 0) )
return result
def lowerCamelCase__ ( snake_case_ : List[Any] , snake_case_ : str ) -> Optional[Any]:
__snake_case = (original_image_slice * 4, 0, tile.size[0], tile.size[1])
__snake_case = tile.crop(snake_case_ )
return tile
def lowerCamelCase__ ( snake_case_ : Any , snake_case_ : int ) -> Optional[int]:
__snake_case = n % d
return n - divisor
class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ):
def __init__(self : Dict , a__ : AutoencoderKL , a__ : CLIPTextModel , a__ : CLIPTokenizer , a__ : UNetaDConditionModel , a__ : DDPMScheduler , a__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , a__ : int = 350 , ):
"""simple docstring"""
super().__init__(
vae=a__ , text_encoder=a__ , tokenizer=a__ , unet=a__ , low_res_scheduler=a__ , scheduler=a__ , max_noise_level=a__ , )
def a (self : Tuple , a__ : str , a__ : int , a__ : Tuple , a__ : List[str] , a__ : Tuple , a__ : str , a__ : Dict , **a__ : List[str] ):
"""simple docstring"""
torch.manual_seed(0 )
__snake_case = (
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 ),
)
__snake_case = add_overlap_rect(a__ , a__ , image.size )
__snake_case = image.crop(a__ )
__snake_case = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
__snake_case = translated_slice_x - (original_image_slice / 2)
__snake_case = max(0 , a__ )
__snake_case = squeeze_tile(a__ , a__ , a__ , a__ )
__snake_case = to_input.size
__snake_case = to_input.resize((tile_size, tile_size) , Image.BICUBIC )
__snake_case = super(a__ , self ).__call__(image=a__ , **a__ ).images[0]
__snake_case = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC )
__snake_case = unsqueeze_tile(a__ , a__ )
__snake_case = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC )
__snake_case = []
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''' )
__snake_case = 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 : Any , a__ : Union[str, List[str]] , a__ : Union[PIL.Image.Image, List[PIL.Image.Image]] , a__ : int = 75 , a__ : float = 9.0 , a__ : int = 50 , a__ : Optional[Union[str, List[str]]] = None , a__ : Optional[int] = 1 , a__ : float = 0.0 , a__ : Optional[torch.Generator] = None , a__ : Optional[torch.FloatTensor] = None , a__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , a__ : int = 1 , a__ : int = 128 , a__ : int = 32 , a__ : int = 32 , ):
"""simple docstring"""
__snake_case = Image.new('''RGB''' , (image.size[0] * 4, image.size[1] * 4) )
__snake_case = math.ceil(image.size[0] / tile_size )
__snake_case = math.ceil(image.size[1] / tile_size )
__snake_case = tcx * tcy
__snake_case = 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__ ( ) -> Tuple:
# Run a demo
__snake_case = '''stabilityai/stable-diffusion-x4-upscaler'''
__snake_case = StableDiffusionTiledUpscalePipeline.from_pretrained(snake_case_ , revision='''fp16''' , torch_dtype=torch.floataa )
__snake_case = pipe.to('''cuda''' )
__snake_case = Image.open('''../../docs/source/imgs/diffusers_library.jpg''' )
def callback(snake_case_ : Any ):
print(f"""progress: {obj['progress']:.4f}""" )
obj["image"].save('''diffusers_library_progress.jpg''' )
__snake_case = pipe(image=snake_case_ , prompt='''Black font, white background, vector''' , noise_level=40 , callback=snake_case_ )
final_image.save('''diffusers_library.jpg''' )
if __name__ == "__main__":
main()
| 592 | 0 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class A_ :
"""simple docstring"""
def __init__( self , __UpperCAmelCase ) -> None:
a : Optional[int] = num_of_nodes
a : list[list[int]] = []
a : dict[int, int] = {}
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> None:
self.m_edges.append([u_node, v_node, weight] )
def lowercase_ ( self , __UpperCAmelCase ) -> int:
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node] )
def lowercase_ ( self , __UpperCAmelCase ) -> None:
if self.m_component[u_node] != u_node:
for k in self.m_component:
a : int = self.find_component(__UpperCAmelCase )
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> None:
if component_size[u_node] <= component_size[v_node]:
a : Union[str, Any] = v_node
component_size[v_node] += component_size[u_node]
self.set_component(__UpperCAmelCase )
elif component_size[u_node] >= component_size[v_node]:
a : Union[str, Any] = self.find_component(__UpperCAmelCase )
component_size[u_node] += component_size[v_node]
self.set_component(__UpperCAmelCase )
def lowercase_ ( self ) -> None:
a : str = []
a : Optional[int] = 0
a : list[Any] = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes ):
self.m_component.update({node: node} )
component_size.append(1 )
a : Union[str, Any] = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
a , a , a : str = edge
a : Optional[int] = self.m_component[u]
a : str = self.m_component[v]
if u_component != v_component:
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
a : List[str] = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(__UpperCAmelCase , __UpperCAmelCase ):
a , a , a : str = edge
a : int = self.m_component[u]
a : int = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
print(f'Added edge [{u} - {v}]\nAdded weight: {w}\n' )
num_of_components -= 1
a : Any = [-1] * self.m_num_of_nodes
print(f'The total weight of the minimal spanning tree is: {mst_weight}' )
def A_ ( ) -> None:
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| 509 |
"""simple docstring"""
from io import BytesIO
from typing import List, Union
import requests
from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_decord_available():
import numpy as np
from decord import VideoReader
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__)
@add_end_docstrings(_UpperCAmelCase )
class A_ ( _UpperCAmelCase ):
"""simple docstring"""
def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict:
super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
requires_backends(self , 'decord' )
self.check_model_type(__UpperCAmelCase )
def lowercase_ ( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None ) -> List[str]:
a : List[str] = {}
if frame_sampling_rate is not None:
a : Tuple = frame_sampling_rate
if num_frames is not None:
a : List[Any] = num_frames
a : Optional[int] = {}
if top_k is not None:
a : int = top_k
return preprocess_params, {}, postprocess_params
def __call__( self , __UpperCAmelCase , **__UpperCAmelCase ) -> Any:
return super().__call__(__UpperCAmelCase , **__UpperCAmelCase )
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=1 ) -> Dict:
if num_frames is None:
a : int = self.model.config.num_frames
if video.startswith('http://' ) or video.startswith('https://' ):
a : int = BytesIO(requests.get(__UpperCAmelCase ).content )
a : Optional[Any] = VideoReader(__UpperCAmelCase )
videoreader.seek(0 )
a : Tuple = 0
a : Dict = num_frames * frame_sampling_rate - 1
a : Optional[Any] = np.linspace(__UpperCAmelCase , __UpperCAmelCase , num=__UpperCAmelCase , dtype=np.intaa )
a : str = videoreader.get_batch(__UpperCAmelCase ).asnumpy()
a : Dict = list(__UpperCAmelCase )
a : Tuple = self.image_processor(__UpperCAmelCase , return_tensors=self.framework )
return model_inputs
def lowercase_ ( self , __UpperCAmelCase ) -> Union[str, Any]:
a : Union[str, Any] = self.model(**__UpperCAmelCase )
return model_outputs
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase=5 ) -> Union[str, Any]:
if top_k > self.model.config.num_labels:
a : Union[str, Any] = self.model.config.num_labels
if self.framework == "pt":
a : List[Any] = model_outputs.logits.softmax(-1 )[0]
a , a : Union[str, Any] = probs.topk(__UpperCAmelCase )
else:
raise ValueError(f'Unsupported framework: {self.framework}' )
a : Tuple = scores.tolist()
a : Any = ids.tolist()
return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__UpperCAmelCase , __UpperCAmelCase )]
| 509 | 1 |
import math
def __snake_case ( __magic_name__ ):
'''simple docstring'''
assert isinstance(__magic_name__ , __magic_name__ ) and (
number >= 0
), "'number' must been an int and positive"
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
# Negatives, 0, 1 and all even numbers are not primes
return False
lowercase = range(3 , int(math.sqrt(__magic_name__ ) + 1 ) , 2 )
return not any(not number % i for i in odd_numbers )
def __snake_case ( __magic_name__ , __magic_name__=1 , **__magic_name__ ):
'''simple docstring'''
lowercase = factor * value
lowercase = value
while not is_prime(__magic_name__ ):
value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1 , **__magic_name__ )
return value
| 441 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_snake_case : Union[str, Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_snake_case : Union[str, Any] = [
"WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST",
"WavLMForAudioFrameClassification",
"WavLMForCTC",
"WavLMForSequenceClassification",
"WavLMForXVector",
"WavLMModel",
"WavLMPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_wavlm import (
WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST,
WavLMForAudioFrameClassification,
WavLMForCTC,
WavLMForSequenceClassification,
WavLMForXVector,
WavLMModel,
WavLMPreTrainedModel,
)
else:
import sys
_snake_case : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 441 | 1 |
import json
import logging
import os
import sys
from pathlib import Path
import finetune_rag
from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
TestCasePlus,
execute_subprocess_async,
require_ray,
require_torch_gpu,
require_torch_multi_gpu,
)
logging.basicConfig(level=logging.DEBUG)
UpperCAmelCase__ : Optional[int] = logging.getLogger()
UpperCAmelCase__ : Union[str, Any] = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class __lowercase ( lowerCamelCase__ ):
def _a ( self , lowercase_) -> Tuple:
os.makedirs(lowercase_ , exist_ok=lowercase_)
__snake_case = {'source': 'What is love ?', 'target': 'life'}
__snake_case = {'train': 1_2, 'val': 2, 'test': 2}
for split in ["train", "test", "val"]:
for field in ["source", "target"]:
__snake_case = '\n'.join([contents[field]] * n_lines[split])
with open(os.path.join(lowercase_ , F"{split}.{field}") , 'w') as f:
f.write(lowercase_)
def _a ( self , lowercase_ , lowercase_ = "pytorch") -> Dict:
__snake_case = self.get_auto_remove_tmp_dir()
__snake_case = os.path.join(lowercase_ , 'output')
__snake_case = os.path.join(lowercase_ , 'data')
self._create_dummy_data(data_dir=lowercase_)
__snake_case = F"\n --data_dir {data_dir} \\n --output_dir {output_dir} \\n --model_name_or_path facebook/rag-sequence-base \\n --model_type rag_sequence \\n --do_train \\n --do_predict \\n --n_val -1 \\n --val_check_interval 1.0 \\n --train_batch_size 2 \\n --eval_batch_size 1 \\n --max_source_length 25 \\n --max_target_length 25 \\n --val_max_target_length 25 \\n --test_max_target_length 25 \\n --label_smoothing 0.1 \\n --dropout 0.1 \\n --attention_dropout 0.1 \\n --weight_decay 0.001 \\n --adam_epsilon 1e-08 \\n --max_grad_norm 0.1 \\n --lr_scheduler polynomial \\n --learning_rate 3e-04 \\n --num_train_epochs 1 \\n --warmup_steps 4 \\n --gradient_accumulation_steps 1 \\n --distributed-port 8787 \\n --use_dummy_dataset 1 \\n --distributed_retriever {distributed_retriever} \\n ".split()
if gpus > 0:
testargs.append(F"--gpus={gpus}")
if is_apex_available():
testargs.append('--fp16')
else:
testargs.append('--gpus=0')
testargs.append('--distributed_backend=ddp_cpu')
testargs.append('--num_processes=2')
__snake_case = [sys.executable, str(Path(finetune_rag.__file__).resolve())] + testargs
execute_subprocess_async(lowercase_ , env=self.get_env())
__snake_case = os.path.join(lowercase_ , 'metrics.json')
with open(lowercase_) as f:
__snake_case = json.load(lowercase_)
return result
@require_torch_gpu
def _a ( self) -> Optional[Any]:
__snake_case = self._run_finetune(gpus=1)
self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2)
@require_torch_multi_gpu
def _a ( self) -> Tuple:
__snake_case = self._run_finetune(gpus=2)
self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2)
@require_torch_gpu
@require_ray
def _a ( self) -> Union[str, Any]:
__snake_case = self._run_finetune(gpus=1 , distributed_retriever='ray')
self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2)
@require_torch_multi_gpu
@require_ray
def _a ( self) -> Dict:
__snake_case = self._run_finetune(gpus=1 , distributed_retriever='ray')
self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2)
| 676 |
import argparse
import os
from pathlib import Path
from typing import Dict
import tensorflow as tf
import torch
from tqdm import tqdm
from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer
from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params
UpperCAmelCase__ : Optional[Any] = [
# replace left string with right string to get the relevant state_dict key (identical state dict to bart)
["memory_attention", "encoder_attn"],
["attention", "attn"],
["/", "."],
[".LayerNorm.gamma", "_layer_norm.weight"],
[".LayerNorm.beta", "_layer_norm.bias"],
["r.layer_", "r.layers."],
["output_proj", "out_proj"],
["ffn.dense_1.", "fc2."],
["ffn.dense.", "fc1."],
["ffn_layer_norm", "final_layer_norm"],
["kernel", "weight"],
["encoder_layer_norm.", "encoder.layer_norm."],
["decoder_layer_norm.", "decoder.layer_norm."],
["embeddings.weights", "shared.weight"],
]
def A ( snake_case__ : List[Any] ) -> str:
'''simple docstring'''
for pegasus_name, hf_name in PATTERNS:
__snake_case = k.replace(snake_case__ , snake_case__ )
return k
def A ( snake_case__ : dict , snake_case__ : dict ) -> PegasusForConditionalGeneration:
'''simple docstring'''
__snake_case = DEFAULTS.copy()
cfg_kwargs.update(snake_case__ )
__snake_case = PegasusConfig(**snake_case__ )
__snake_case = PegasusForConditionalGeneration(snake_case__ )
__snake_case = torch_model.model.state_dict()
__snake_case = {}
for k, v in tf_weights.items():
__snake_case = rename_state_dict_key(snake_case__ )
if new_k not in sd:
raise ValueError(f"could not find new key {new_k} in state dict. (converted from {k})" )
if "dense" in k or "proj" in new_k:
__snake_case = v.T
__snake_case = torch.tensor(snake_case__ , dtype=sd[new_k].dtype )
assert v.shape == sd[new_k].shape, f"{new_k}, {k}, {v.shape}, {sd[new_k].shape}"
# make sure embedding.padding_idx is respected
__snake_case = torch.zeros_like(mapping['shared.weight'][cfg.pad_token_id + 1] )
__snake_case = mapping['shared.weight']
__snake_case = mapping['shared.weight']
__snake_case = {k: torch.zeros_like(snake_case__ ) for k, v in sd.items() if k.endswith('bias' ) and k not in mapping}
mapping.update(**snake_case__ )
__snake_case , __snake_case = torch_model.model.load_state_dict(snake_case__ , strict=snake_case__ )
__snake_case = [
k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.weight']
]
assert unexpected_missing == [], f"no matches found for the following torch keys {unexpected_missing}"
assert extra == [], f"no matches found for the following tf keys {extra}"
return torch_model
def A ( snake_case__ : Optional[int]="./ckpt/aeslc/model.ckpt-32000" ) -> Dict:
'''simple docstring'''
__snake_case = tf.train.list_variables(snake_case__ )
__snake_case = {}
__snake_case = ['Adafactor', 'global_step']
for name, shape in tqdm(snake_case__ , desc='converting tf checkpoint to dict' ):
__snake_case = any(pat in name for pat in ignore_name )
if skip_key:
continue
__snake_case = tf.train.load_variable(snake_case__ , snake_case__ )
__snake_case = array
return tf_weights
def A ( snake_case__ : str , snake_case__ : str ) -> Tuple:
'''simple docstring'''
# save tokenizer first
__snake_case = Path(snake_case__ ).parent.name
__snake_case = task_specific_params[f"summarization_{dataset}"]['max_position_embeddings']
__snake_case = PegasusTokenizer.from_pretrained('sshleifer/pegasus' , model_max_length=snake_case__ )
assert tok.model_max_length == desired_max_model_length
tok.save_pretrained(snake_case__ )
# convert model
__snake_case = get_tf_weights_as_numpy(snake_case__ )
__snake_case = task_specific_params[f"summarization_{dataset}"]
if dataset == "large":
__snake_case = task_specific_params
__snake_case = convert_pegasus(snake_case__ , snake_case__ )
torch_model.save_pretrained(snake_case__ )
__snake_case = torch_model.state_dict()
sd.pop('model.decoder.embed_positions.weight' )
sd.pop('model.encoder.embed_positions.weight' )
torch.save(snake_case__ , Path(snake_case__ ) / 'pytorch_model.bin' )
if __name__ == "__main__":
UpperCAmelCase__ : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument("tf_ckpt_path", type=str, help="passed to tf.train.list_variables")
parser.add_argument("save_dir", default=None, type=str, help="Path to the output PyTorch model.")
UpperCAmelCase__ : int = parser.parse_args()
if args.save_dir is None:
UpperCAmelCase__ : List[str] = Path(args.tf_ckpt_path).parent.name
UpperCAmelCase__ : str = os.path.join("pegasus", dataset)
convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
| 676 | 1 |
import os
from collections.abc import Iterator
def lowerCAmelCase_ ( __lowerCamelCase = "." ):
for dir_path, dir_names, filenames in os.walk(__lowerCamelCase ):
__snake_case : Tuple = [d for d in dir_names if d != "scripts" and d[0] not in "._"]
for filename in filenames:
if filename == "__init__.py":
continue
if os.path.splitext(__lowerCamelCase )[1] in (".py", ".ipynb"):
yield os.path.join(__lowerCamelCase , __lowerCamelCase ).lstrip("./" )
def lowerCAmelCase_ ( __lowerCamelCase ):
return F'{i * " "}*' if i else "\n##"
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ):
__snake_case : List[str] = old_path.split(os.sep )
for i, new_part in enumerate(new_path.split(os.sep ) ):
if (i + 1 > len(__lowerCamelCase ) or old_parts[i] != new_part) and new_part:
print(F'{md_prefix(__lowerCamelCase )} {new_part.replace("_" , " " ).title()}' )
return new_path
def lowerCAmelCase_ ( __lowerCamelCase = "." ):
__snake_case : Any = ""
for filepath in sorted(good_file_paths(__lowerCamelCase ) ):
__snake_case , __snake_case : Any = os.path.split(__lowerCamelCase )
if filepath != old_path:
__snake_case : str = print_path(__lowerCamelCase , __lowerCamelCase )
__snake_case : Union[str, Any] = (filepath.count(os.sep ) + 1) if filepath else 0
__snake_case : List[Any] = F'{filepath}/{filename}'.replace(" " , "%20" )
__snake_case : str = os.path.splitext(filename.replace("_" , " " ).title() )[0]
print(F'{md_prefix(__lowerCamelCase )} [{filename}]({url})' )
if __name__ == "__main__":
print_directory_md(".")
| 81 |
'''simple docstring'''
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex
# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V,
# or u belongs to V and v to U. We can also say that there is no edge that connects
# vertices of same set.
def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ):
_snake_case = [False] * len(_SCREAMING_SNAKE_CASE )
_snake_case = [-1] * len(_SCREAMING_SNAKE_CASE )
def dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
_snake_case = True
_snake_case = c
for u in graph[v]:
if not visited[u]:
dfs(_SCREAMING_SNAKE_CASE , 1 - c )
for i in range(len(_SCREAMING_SNAKE_CASE ) ):
if not visited[i]:
dfs(_SCREAMING_SNAKE_CASE , 0 )
for i in range(len(_SCREAMING_SNAKE_CASE ) ):
for j in graph[i]:
if color[i] == color[j]:
return False
return True
# Adjacency list of graph
__lowerCAmelCase = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []}
print(check_bipartite_dfs(graph)) | 585 | 0 |
from itertools import count
def lowerCamelCase_ ( lowerCAmelCase__ : int = 50 ) -> int:
'''simple docstring'''
A = [1] * min_block_length
for n in count(lowerCAmelCase__ ):
fill_count_functions.append(1 )
for block_length in range(lowerCAmelCase__ , n + 1 ):
for block_start in range(n - block_length ):
fill_count_functions[n] += fill_count_functions[
n - block_start - block_length - 1
]
fill_count_functions[n] += 1
if fill_count_functions[n] > 1000000:
break
return n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 720 |
import inspect
import math
import tempfile
import unittest
import numpy as np
from transformers import ViTMAEConfig
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 ViTMAEForPreTraining, ViTMAEModel
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 lowerCAmelCase__ :
def __init__( self : str , __UpperCamelCase : Any , __UpperCamelCase : Dict=13 , __UpperCamelCase : Tuple=30 , __UpperCamelCase : Union[str, Any]=2 , __UpperCamelCase : Optional[int]=3 , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : str=True , __UpperCamelCase : Dict=32 , __UpperCamelCase : Tuple=5 , __UpperCamelCase : List[str]=4 , __UpperCamelCase : str=37 , __UpperCamelCase : Optional[int]="gelu" , __UpperCamelCase : int=0.1 , __UpperCamelCase : Tuple=0.1 , __UpperCamelCase : int=10 , __UpperCamelCase : Union[str, Any]=0.0_2 , __UpperCamelCase : Dict=3 , __UpperCamelCase : Any=0.6 , __UpperCamelCase : List[Any]=None , ) -> List[str]:
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 = mask_ratio
A = scope
# in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
# (we add 1 for the [CLS] token)
A = (image_size // patch_size) ** 2
A = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) )
def __UpperCamelCase ( self : Tuple ) -> str:
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 __UpperCamelCase ( self : int ) -> List[Any]:
return ViTMAEConfig(
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 , mask_ratio=self.mask_ratio , )
def __UpperCamelCase ( self : Any , __UpperCamelCase : Dict , __UpperCamelCase : List[str] , __UpperCamelCase : Tuple ) -> Union[str, Any]:
A = ViTMAEModel(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 __UpperCamelCase ( self : List[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : int , __UpperCamelCase : List[str] ) -> Optional[int]:
A = ViTMAEForPreTraining(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
A = model(__UpperCamelCase )
A = (self.image_size // self.patch_size) ** 2
A = self.patch_size**2 * self.num_channels
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
# test greyscale images
A = 1
A = ViTMAEForPreTraining(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
A = model(__UpperCamelCase )
A = self.patch_size**2
self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) )
def __UpperCamelCase ( self : Union[str, Any] ) -> int:
A = self.prepare_config_and_inputs()
A , A , A = config_and_inputs
A = {'pixel_values': pixel_values}
return config, inputs_dict
@require_torch
class lowerCAmelCase__ ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ):
A_ : Tuple = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else ()
A_ : List[str] = {'feature-extraction': ViTMAEModel} if is_torch_available() else {}
A_ : Tuple = False
A_ : str = False
A_ : Tuple = False
A_ : Union[str, Any] = False
def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]:
A = ViTMAEModelTester(self )
A = ConfigTester(self , config_class=__UpperCamelCase , has_text_modality=__UpperCamelCase , hidden_size=37 )
def __UpperCamelCase ( self : Optional[int] ) -> str:
self.config_tester.run_common_tests()
@unittest.skip(reason='ViTMAE does not use inputs_embeds' )
def __UpperCamelCase ( self : Any ) -> List[Any]:
pass
def __UpperCamelCase ( self : Tuple ) -> 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 __UpperCamelCase ( self : Union[str, Any] ) -> int:
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 __UpperCamelCase ( self : Any ) -> List[Any]:
A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCamelCase )
def __UpperCamelCase ( self : str ) -> List[str]:
A = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__UpperCamelCase )
def __UpperCamelCase ( self : List[str] , __UpperCamelCase : List[str] , __UpperCamelCase : Dict , __UpperCamelCase : Tuple ) -> int:
# make masks reproducible
np.random.seed(2 )
A = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 )
A = np.random.uniform(size=(self.model_tester.batch_size, num_patches) )
A = torch.from_numpy(__UpperCamelCase )
# Add `noise` argument.
# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
A = pt_noise
super().check_pt_tf_models(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
def __UpperCamelCase ( self : List[Any] ) -> List[str]:
A , A = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
A = model_class(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
# make random mask reproducible
torch.manual_seed(2 )
with torch.no_grad():
A = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
A = outputs[0].cpu().numpy()
A = 0
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(__UpperCamelCase )
A = model_class.from_pretrained(__UpperCamelCase )
model.to(__UpperCamelCase )
# make random mask reproducible
torch.manual_seed(2 )
with torch.no_grad():
A = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
# Make sure we don't have nans
A = after_outputs[0].cpu().numpy()
A = 0
A = np.amax(np.abs(out_a - out_a ) )
self.assertLessEqual(__UpperCamelCase , 1e-5 )
@unittest.skip(
reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' )
def __UpperCamelCase ( self : Optional[Any] ) -> int:
pass
@unittest.skip(
reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' )
def __UpperCamelCase ( self : List[Any] ) -> int:
pass
@unittest.skip(
reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' )
def __UpperCamelCase ( self : int ) -> Dict:
pass
@unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load' )
def __UpperCamelCase ( self : List[Any] ) -> Any:
pass
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def __UpperCamelCase ( self : Tuple ) -> Optional[Any]:
pass
@slow
def __UpperCamelCase ( self : Tuple ) -> Tuple:
for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
A = ViTMAEModel.from_pretrained(__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
def lowerCamelCase_ ( ) -> Optional[Any]:
'''simple docstring'''
A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
@require_vision
class lowerCAmelCase__ ( unittest.TestCase ):
@cached_property
def __UpperCamelCase ( self : Any ) -> Any:
return ViTImageProcessor.from_pretrained('facebook/vit-mae-base' ) if is_vision_available() else None
@slow
def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]:
# make random mask reproducible across the PT and TF model
np.random.seed(2 )
A = ViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base' ).to(__UpperCamelCase )
A = self.default_image_processor
A = prepare_img()
A = image_processor(images=__UpperCamelCase , return_tensors='pt' ).to(__UpperCamelCase )
# prepare a noise vector that will be also used for testing the TF model
# (this way we can ensure that the PT and TF models operate on the same inputs)
A = ViTMAEConfig()
A = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 )
A = np.random.uniform(size=(1, num_patches) )
# forward pass
with torch.no_grad():
A = model(**__UpperCamelCase , noise=torch.from_numpy(__UpperCamelCase ).to(device=__UpperCamelCase ) )
# verify the logits
A = torch.Size((1, 196, 768) )
self.assertEqual(outputs.logits.shape , __UpperCamelCase )
A = torch.tensor(
[[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(__UpperCamelCase ) , atol=1e-4 ) ) | 224 | 0 |
"""simple docstring"""
import copy
import os
from typing import TYPE_CHECKING, List, Union
if TYPE_CHECKING:
pass
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCamelCase = logging.get_logger(__name__)
__lowerCamelCase = {
"kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json",
}
class _snake_case ( A__ ):
'''simple docstring'''
UpperCamelCase__ ="""align_text_model"""
def __init__( self : List[Any] , snake_case : Tuple=30_522 , snake_case : Any=768 , snake_case : str=12 , snake_case : Optional[Any]=12 , snake_case : str=3_072 , snake_case : int="gelu" , snake_case : List[Any]=0.1 , snake_case : str=0.1 , snake_case : Optional[int]=512 , snake_case : str=2 , snake_case : Optional[int]=0.02 , snake_case : int=1e-12 , snake_case : Any=0 , snake_case : Optional[int]="absolute" , snake_case : List[Any]=True , **snake_case : Tuple , ):
super().__init__(**snake_case )
UpperCAmelCase_ :Optional[Any] = vocab_size
UpperCAmelCase_ :Union[str, Any] = hidden_size
UpperCAmelCase_ :Optional[int] = num_hidden_layers
UpperCAmelCase_ :Any = num_attention_heads
UpperCAmelCase_ :int = hidden_act
UpperCAmelCase_ :Any = intermediate_size
UpperCAmelCase_ :str = hidden_dropout_prob
UpperCAmelCase_ :str = attention_probs_dropout_prob
UpperCAmelCase_ :Any = max_position_embeddings
UpperCAmelCase_ :Dict = type_vocab_size
UpperCAmelCase_ :int = initializer_range
UpperCAmelCase_ :List[str] = layer_norm_eps
UpperCAmelCase_ :Optional[Any] = position_embedding_type
UpperCAmelCase_ :Dict = use_cache
UpperCAmelCase_ :Tuple = pad_token_id
@classmethod
def snake_case_ ( cls : int , snake_case : Union[str, os.PathLike] , **snake_case : Dict ):
cls._set_token_in_kwargs(snake_case )
UpperCAmelCase_ ,UpperCAmelCase_ :Optional[int] = cls.get_config_dict(snake_case , **snake_case )
# get the text config dict if we are loading from AlignConfig
if config_dict.get('''model_type''' ) == "align":
UpperCAmelCase_ :List[str] = config_dict['''text_config''']
if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(snake_case , **snake_case )
class _snake_case ( A__ ):
'''simple docstring'''
UpperCamelCase__ ="""align_vision_model"""
def __init__( self : Dict , snake_case : int = 3 , snake_case : int = 600 , snake_case : float = 2.0 , snake_case : float = 3.1 , snake_case : int = 8 , snake_case : List[int] = [3, 3, 5, 3, 5, 5, 3] , snake_case : List[int] = [32, 16, 24, 40, 80, 112, 192] , snake_case : List[int] = [16, 24, 40, 80, 112, 192, 320] , snake_case : List[int] = [] , snake_case : List[int] = [1, 2, 2, 2, 1, 2, 1] , snake_case : List[int] = [1, 2, 2, 3, 3, 4, 1] , snake_case : List[int] = [1, 6, 6, 6, 6, 6, 6] , snake_case : float = 0.25 , snake_case : str = "swish" , snake_case : int = 2_560 , snake_case : str = "mean" , snake_case : float = 0.02 , snake_case : float = 0.001 , snake_case : float = 0.99 , snake_case : float = 0.2 , **snake_case : int , ):
super().__init__(**snake_case )
UpperCAmelCase_ :str = num_channels
UpperCAmelCase_ :str = image_size
UpperCAmelCase_ :List[str] = width_coefficient
UpperCAmelCase_ :Any = depth_coefficient
UpperCAmelCase_ :Any = depth_divisor
UpperCAmelCase_ :int = kernel_sizes
UpperCAmelCase_ :List[Any] = in_channels
UpperCAmelCase_ :Dict = out_channels
UpperCAmelCase_ :List[str] = depthwise_padding
UpperCAmelCase_ :Dict = strides
UpperCAmelCase_ :Optional[int] = num_block_repeats
UpperCAmelCase_ :Optional[Any] = expand_ratios
UpperCAmelCase_ :str = squeeze_expansion_ratio
UpperCAmelCase_ :Tuple = hidden_act
UpperCAmelCase_ :Dict = hidden_dim
UpperCAmelCase_ :Any = pooling_type
UpperCAmelCase_ :Any = initializer_range
UpperCAmelCase_ :str = batch_norm_eps
UpperCAmelCase_ :Union[str, Any] = batch_norm_momentum
UpperCAmelCase_ :Dict = drop_connect_rate
UpperCAmelCase_ :Union[str, Any] = sum(snake_case ) * 4
@classmethod
def snake_case_ ( cls : Dict , snake_case : Union[str, os.PathLike] , **snake_case : Optional[int] ):
cls._set_token_in_kwargs(snake_case )
UpperCAmelCase_ ,UpperCAmelCase_ :List[str] = cls.get_config_dict(snake_case , **snake_case )
# get the vision config dict if we are loading from AlignConfig
if config_dict.get('''model_type''' ) == "align":
UpperCAmelCase_ :Tuple = config_dict['''vision_config''']
if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )
return cls.from_dict(snake_case , **snake_case )
class _snake_case ( A__ ):
'''simple docstring'''
UpperCamelCase__ ="""align"""
UpperCamelCase__ =True
def __init__( self : List[str] , snake_case : List[str]=None , snake_case : Optional[int]=None , snake_case : Union[str, Any]=640 , snake_case : int=1.0 , snake_case : Any=0.02 , **snake_case : Optional[int] , ):
super().__init__(**snake_case )
if text_config is None:
UpperCAmelCase_ :Optional[Any] = {}
logger.info('''text_config is None. Initializing the AlignTextConfig with default values.''' )
if vision_config is None:
UpperCAmelCase_ :int = {}
logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.''' )
UpperCAmelCase_ :int = AlignTextConfig(**snake_case )
UpperCAmelCase_ :Any = AlignVisionConfig(**snake_case )
UpperCAmelCase_ :Dict = projection_dim
UpperCAmelCase_ :Dict = temperature_init_value
UpperCAmelCase_ :List[Any] = initializer_range
@classmethod
def snake_case_ ( cls : str , snake_case : AlignTextConfig , snake_case : AlignVisionConfig , **snake_case : int ):
return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case )
def snake_case_ ( self : Optional[Any] ):
UpperCAmelCase_ :List[Any] = copy.deepcopy(self.__dict__ )
UpperCAmelCase_ :Tuple = self.text_config.to_dict()
UpperCAmelCase_ :Dict = self.vision_config.to_dict()
UpperCAmelCase_ :int = self.__class__.model_type
return output
| 608 |
"""simple docstring"""
import math
import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def a ( __snake_case : int = 3 ):
'''simple docstring'''
if isinstance(__snake_case, __snake_case ):
raise TypeError('''number of qubits must be a integer.''' )
if number_of_qubits <= 0:
raise ValueError('''number of qubits must be > 0.''' )
if math.floor(__snake_case ) != number_of_qubits:
raise ValueError('''number of qubits must be exact integer.''' )
if number_of_qubits > 10:
raise ValueError('''number of qubits too large to simulate(>10).''' )
UpperCAmelCase_ :Optional[int] = QuantumRegister(__snake_case, '''qr''' )
UpperCAmelCase_ :int = ClassicalRegister(__snake_case, '''cr''' )
UpperCAmelCase_ :str = QuantumCircuit(__snake_case, __snake_case )
UpperCAmelCase_ :List[str] = number_of_qubits
for i in range(__snake_case ):
quantum_circuit.h(number_of_qubits - i - 1 )
counter -= 1
for j in range(__snake_case ):
quantum_circuit.cp(np.pi / 2 ** (counter - j), __snake_case, __snake_case )
for k in range(number_of_qubits // 2 ):
quantum_circuit.swap(__snake_case, number_of_qubits - k - 1 )
# measure all the qubits
quantum_circuit.measure(__snake_case, __snake_case )
# simulate with 10000 shots
UpperCAmelCase_ :List[Any] = Aer.get_backend('''qasm_simulator''' )
UpperCAmelCase_ :Dict = execute(__snake_case, __snake_case, shots=10000 )
return job.result().get_counts(__snake_case )
if __name__ == "__main__":
print(
f'''Total count for quantum fourier transform state is: \
{quantum_fourier_transform(3)}'''
)
| 608 | 1 |
from __future__ import annotations
from typing import Any
def a_ (_lowerCAmelCase : list )-> Any:
if not postfix_notation:
return 0
snake_case: Any = {"""+""", """-""", """*""", """/"""}
snake_case: Optional[int] = []
for token in postfix_notation:
if token in operations:
snake_case , snake_case: Union[str, Any] = stack.pop(), stack.pop()
if token == "+":
stack.append(a + b )
elif token == "-":
stack.append(a - b )
elif token == "*":
stack.append(a * b )
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1 )
else:
stack.append(a // b )
else:
stack.append(int(_lowerCamelCase ) )
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod()
| 700 | import unittest
from transformers import BigBirdConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax
from transformers.models.big_bird.modeling_flax_big_bird import (
FlaxBigBirdForCausalLM,
FlaxBigBirdForMaskedLM,
FlaxBigBirdForMultipleChoice,
FlaxBigBirdForPreTraining,
FlaxBigBirdForQuestionAnswering,
FlaxBigBirdForSequenceClassification,
FlaxBigBirdForTokenClassification,
FlaxBigBirdModel,
)
class lowerCamelCase ( unittest.TestCase ):
def __init__( self , __lowerCamelCase , __lowerCamelCase=2 , __lowerCamelCase=56 , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase=99 , __lowerCamelCase=32 , __lowerCamelCase=2 , __lowerCamelCase=2 , __lowerCamelCase=7 , __lowerCamelCase="gelu_new" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=5_12 , __lowerCamelCase=16 , __lowerCamelCase=2 , __lowerCamelCase=0.02 , __lowerCamelCase=4 , __lowerCamelCase="block_sparse" , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=2 , __lowerCamelCase=3 , ) -> int:
'''simple docstring'''
snake_case: str = parent
snake_case: Any = batch_size
snake_case: List[str] = seq_length
snake_case: str = is_training
snake_case: List[str] = use_attention_mask
snake_case: Optional[Any] = use_token_type_ids
snake_case: Union[str, Any] = use_labels
snake_case: Dict = vocab_size
snake_case: Dict = hidden_size
snake_case: Optional[Any] = num_hidden_layers
snake_case: int = num_attention_heads
snake_case: List[Any] = intermediate_size
snake_case: Optional[Any] = hidden_act
snake_case: List[str] = hidden_dropout_prob
snake_case: Dict = attention_probs_dropout_prob
snake_case: Optional[Any] = max_position_embeddings
snake_case: str = type_vocab_size
snake_case: Dict = type_sequence_label_size
snake_case: List[Any] = initializer_range
snake_case: str = num_choices
snake_case: Any = rescale_embeddings
snake_case: int = attention_type
snake_case: int = use_bias
snake_case: List[str] = block_size
snake_case: Any = num_random_blocks
def lowerCAmelCase_ ( self ) -> Any:
'''simple docstring'''
snake_case: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case: Tuple = None
if self.use_attention_mask:
snake_case: Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] )
snake_case: Tuple = None
if self.use_token_type_ids:
snake_case: Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
snake_case: Any = BigBirdConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , )
return config, input_ids, token_type_ids, attention_mask
def lowerCAmelCase_ ( self ) -> List[Any]:
'''simple docstring'''
snake_case: Union[str, Any] = self.prepare_config_and_inputs()
snake_case , snake_case , snake_case , snake_case: List[Any] = config_and_inputs
snake_case: Any = {
"""input_ids""": input_ids,
"""token_type_ids""": token_type_ids,
"""attention_mask""": attention_mask,
}
return config, inputs_dict
@require_flax
class lowerCamelCase ( __snake_case , unittest.TestCase ):
__lowerCamelCase = (
(
FlaxBigBirdForCausalLM,
FlaxBigBirdModel,
FlaxBigBirdForPreTraining,
FlaxBigBirdForMaskedLM,
FlaxBigBirdForMultipleChoice,
FlaxBigBirdForQuestionAnswering,
FlaxBigBirdForSequenceClassification,
FlaxBigBirdForTokenClassification,
)
if is_flax_available()
else ()
)
__lowerCamelCase = False
__lowerCamelCase = False
def lowerCAmelCase_ ( self ) -> Any:
'''simple docstring'''
snake_case: List[Any] = FlaxBigBirdModelTester(self )
@slow
# copied from `test_modeling_flax_common` because it takes much longer than other models
def lowerCAmelCase_ ( self ) -> int:
'''simple docstring'''
super().test_from_pretrained_save_pretrained()
@slow
# copied from `test_modeling_flax_common` because it takes much longer than other models
def lowerCAmelCase_ ( self ) -> str:
'''simple docstring'''
super().test_from_pretrained_with_no_automatic_init()
@slow
# copied from `test_modeling_flax_common` because it takes much longer than other models
def lowerCAmelCase_ ( self ) -> Tuple:
'''simple docstring'''
super().test_no_automatic_init()
@slow
# copied from `test_modeling_flax_common` because it takes much longer than other models
def lowerCAmelCase_ ( self ) -> Union[str, Any]:
'''simple docstring'''
super().test_hidden_states_output()
@slow
def lowerCAmelCase_ ( self ) -> Optional[int]:
'''simple docstring'''
for model_class_name in self.all_model_classes:
snake_case: Optional[Any] = model_class_name.from_pretrained("""google/bigbird-roberta-base""" )
self.assertIsNotNone(__lowerCamelCase )
def lowerCAmelCase_ ( self ) -> List[str]:
'''simple docstring'''
if self.test_attn_probs:
super().test_attention_outputs()
@slow
# copied from `test_modeling_flax_common` because it takes much longer than other models
def lowerCAmelCase_ ( self ) -> Tuple:
'''simple docstring'''
snake_case , snake_case: Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
snake_case: Optional[Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase )
snake_case: Tuple = model_class(__lowerCamelCase )
@jax.jit
def model_jitted(__lowerCamelCase , __lowerCamelCase=None , **__lowerCamelCase ):
return model(input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase , **__lowerCamelCase )
with self.subTest("""JIT Enabled""" ):
snake_case: Union[str, Any] = model_jitted(**__lowerCamelCase ).to_tuple()
with self.subTest("""JIT Disabled""" ):
with jax.disable_jit():
snake_case: List[str] = model_jitted(**__lowerCamelCase ).to_tuple()
self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) )
for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase ):
self.assertEqual(jitted_output.shape , output.shape )
def lowerCAmelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=1e-5 , __lowerCamelCase="outputs" , __lowerCamelCase=None ) -> List[str]:
'''simple docstring'''
if name.startswith("""outputs.attentions""" ):
return
else:
super().check_pt_flax_outputs(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
| 164 | 0 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCAmelCase__ : Optional[Any] = {"configuration_timm_backbone": ["TimmBackboneConfig"]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase__ : List[str] = ["TimmBackbone"]
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
UpperCAmelCase__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 48 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__magic_name__ = {
'''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''],
'''tokenization_electra''': ['''ElectraTokenizer'''],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = ['''ElectraTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'''ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ElectraForCausalLM''',
'''ElectraForMaskedLM''',
'''ElectraForMultipleChoice''',
'''ElectraForPreTraining''',
'''ElectraForQuestionAnswering''',
'''ElectraForSequenceClassification''',
'''ElectraForTokenClassification''',
'''ElectraModel''',
'''ElectraPreTrainedModel''',
'''load_tf_weights_in_electra''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'''TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFElectraForMaskedLM''',
'''TFElectraForMultipleChoice''',
'''TFElectraForPreTraining''',
'''TFElectraForQuestionAnswering''',
'''TFElectraForSequenceClassification''',
'''TFElectraForTokenClassification''',
'''TFElectraModel''',
'''TFElectraPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__magic_name__ = [
'''FlaxElectraForCausalLM''',
'''FlaxElectraForMaskedLM''',
'''FlaxElectraForMultipleChoice''',
'''FlaxElectraForPreTraining''',
'''FlaxElectraForQuestionAnswering''',
'''FlaxElectraForSequenceClassification''',
'''FlaxElectraForTokenClassification''',
'''FlaxElectraModel''',
'''FlaxElectraPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig
from .tokenization_electra import ElectraTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_electra_fast import ElectraTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_electra import (
ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
ElectraForCausalLM,
ElectraForMaskedLM,
ElectraForMultipleChoice,
ElectraForPreTraining,
ElectraForQuestionAnswering,
ElectraForSequenceClassification,
ElectraForTokenClassification,
ElectraModel,
ElectraPreTrainedModel,
load_tf_weights_in_electra,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_electra import (
TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFElectraForMaskedLM,
TFElectraForMultipleChoice,
TFElectraForPreTraining,
TFElectraForQuestionAnswering,
TFElectraForSequenceClassification,
TFElectraForTokenClassification,
TFElectraModel,
TFElectraPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_electra import (
FlaxElectraForCausalLM,
FlaxElectraForMaskedLM,
FlaxElectraForMultipleChoice,
FlaxElectraForPreTraining,
FlaxElectraForQuestionAnswering,
FlaxElectraForSequenceClassification,
FlaxElectraForTokenClassification,
FlaxElectraModel,
FlaxElectraPreTrainedModel,
)
else:
import sys
__magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 657 | 0 |
'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest
from multiprocessing import get_context
from pathlib import Path
import datasets
import numpy as np
from datasets import load_dataset
from parameterized import parameterized
from transformers import AutoProcessor
from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available
from ..wavaveca.test_feature_extraction_wavaveca import floats_list
if is_pyctcdecode_available():
from huggingface_hub import snapshot_download
from pyctcdecode import BeamSearchDecoderCTC
from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM
from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput
if is_torch_available():
from transformers import WavaVecaForCTC
@require_pyctcdecode
class __A ( unittest.TestCase ):
'''simple docstring'''
def a__ (self ) -> Tuple:
"""simple docstring"""
_a = '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split()
_a = dict(zip(A , range(len(A ) ) ) )
_a = {
'''unk_token''': '''<unk>''',
'''bos_token''': '''<s>''',
'''eos_token''': '''</s>''',
}
_a = {
'''feature_size''': 1,
'''padding_value''': 0.0,
'''sampling_rate''': 16_000,
'''return_attention_mask''': False,
'''do_normalize''': True,
}
_a = tempfile.mkdtemp()
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
_a = os.path.join(self.tmpdirname , A )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(A ) + '''\n''' )
with open(self.feature_extraction_file , '''w''' , encoding='''utf-8''' ) as fp:
fp.write(json.dumps(A ) + '''\n''' )
# load decoder from hub
_a = '''hf-internal-testing/ngram-beam-search-decoder'''
def a__ (self , **A ) -> Optional[Any]:
"""simple docstring"""
_a = self.add_kwargs_tokens_map.copy()
kwargs.update(A )
return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **A )
def a__ (self , **A ) -> Dict:
"""simple docstring"""
return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **A )
def a__ (self , **A ) -> Dict:
"""simple docstring"""
return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **A )
def a__ (self ) -> Any:
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def a__ (self ) -> Optional[Any]:
"""simple docstring"""
_a = self.get_tokenizer()
_a = self.get_feature_extractor()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
processor.save_pretrained(self.tmpdirname )
_a = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname )
# tokenizer
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , A )
# feature extractor
self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() )
self.assertIsInstance(processor.feature_extractor , A )
# decoder
self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels )
self.assertEqual(
processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , )
self.assertIsInstance(processor.decoder , A )
def a__ (self ) -> List[str]:
"""simple docstring"""
_a = WavaVecaProcessorWithLM(
tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() )
processor.save_pretrained(self.tmpdirname )
# make sure that error is thrown when decoder alphabet doesn't match
_a = WavaVecaProcessorWithLM.from_pretrained(
self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 )
# decoder
self.assertEqual(processor.language_model.alpha , 5.0 )
self.assertEqual(processor.language_model.beta , 3.0 )
self.assertEqual(processor.language_model.score_boundary , -7.0 )
self.assertEqual(processor.language_model.unk_score_offset , 3 )
def a__ (self ) -> List[str]:
"""simple docstring"""
_a = self.get_tokenizer()
# add token to trigger raise
tokenizer.add_tokens(['''xx'''] )
with self.assertRaisesRegex(A , '''include''' ):
WavaVecaProcessorWithLM(
tokenizer=A , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() )
def a__ (self ) -> List[Any]:
"""simple docstring"""
_a = self.get_feature_extractor()
_a = self.get_tokenizer()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
_a = floats_list((3, 1_000) )
_a = feature_extractor(A , return_tensors='''np''' )
_a = processor(A , return_tensors='''np''' )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 )
def a__ (self ) -> Union[str, Any]:
"""simple docstring"""
_a = self.get_feature_extractor()
_a = self.get_tokenizer()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
_a = '''This is a test string'''
_a = processor(text=A )
_a = tokenizer(A )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def a__ (self , A=(2, 10, 16) , A=77 ) -> Any:
"""simple docstring"""
np.random.seed(A )
return np.random.rand(*A )
def a__ (self ) -> Any:
"""simple docstring"""
_a = self.get_feature_extractor()
_a = self.get_tokenizer()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
_a = self._get_dummy_logits(shape=(10, 16) , seed=13 )
_a = processor.decode(A )
_a = decoder.decode_beams(A )[0]
self.assertEqual(decoded_decoder[0] , decoded_processor.text )
self.assertEqual('''</s> <s> </s>''' , decoded_processor.text )
self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score )
self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score )
@parameterized.expand([[None], ['''fork'''], ['''spawn''']] )
def a__ (self , A ) -> Union[str, Any]:
"""simple docstring"""
_a = self.get_feature_extractor()
_a = self.get_tokenizer()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
_a = self._get_dummy_logits()
# note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM.
# otherwise, the LM won't be available to the pool's sub-processes.
# manual logic used to allow parameterized test for both pool=None and pool=Pool(...)
if pool_context is None:
_a = processor.batch_decode(A )
else:
with get_context(A ).Pool() as pool:
_a = processor.batch_decode(A , A )
_a = list(A )
with get_context('''fork''' ).Pool() as p:
_a = decoder.decode_beams_batch(A , A )
_a = [], [], []
for beams in decoded_beams:
texts_decoder.append(beams[0][0] )
logit_scores_decoder.append(beams[0][-2] )
lm_scores_decoder.append(beams[0][-1] )
self.assertListEqual(A , decoded_processor.text )
self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] , decoded_processor.text )
self.assertListEqual(A , decoded_processor.logit_score )
self.assertListEqual(A , decoded_processor.lm_score )
def a__ (self ) -> List[Any]:
"""simple docstring"""
_a = self.get_feature_extractor()
_a = self.get_tokenizer()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
_a = self._get_dummy_logits()
_a = 15
_a = -20.0
_a = -4.0
_a = processor.batch_decode(
A , beam_width=A , beam_prune_logp=A , token_min_logp=A , )
_a = decoded_processor_out.text
_a = list(A )
with get_context('''fork''' ).Pool() as pool:
_a = decoder.decode_beams_batch(
A , A , beam_width=A , beam_prune_logp=A , token_min_logp=A , )
_a = [d[0][0] for d in decoded_decoder_out]
_a = [d[0][2] for d in decoded_decoder_out]
_a = [d[0][3] for d in decoded_decoder_out]
self.assertListEqual(A , A )
self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] , A )
self.assertTrue(np.array_equal(A , decoded_processor_out.logit_score ) )
self.assertTrue(np.allclose([-20.054, -18.447] , A , atol=1E-3 ) )
self.assertTrue(np.array_equal(A , decoded_processor_out.lm_score ) )
self.assertTrue(np.allclose([-15.554, -13.9474] , A , atol=1E-3 ) )
def a__ (self ) -> Any:
"""simple docstring"""
_a = self.get_feature_extractor()
_a = self.get_tokenizer()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
_a = self._get_dummy_logits()
_a = 2.0
_a = 5.0
_a = -20.0
_a = True
_a = processor.batch_decode(
A , alpha=A , beta=A , unk_score_offset=A , lm_score_boundary=A , )
_a = decoded_processor_out.text
_a = list(A )
decoder.reset_params(
alpha=A , beta=A , unk_score_offset=A , lm_score_boundary=A , )
with get_context('''fork''' ).Pool() as pool:
_a = decoder.decode_beams_batch(
A , A , )
_a = [d[0][0] for d in decoded_decoder_out]
self.assertListEqual(A , A )
self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] , A )
_a = processor.decoder.model_container[processor.decoder._model_key]
self.assertEqual(lm_model.alpha , 2.0 )
self.assertEqual(lm_model.beta , 5.0 )
self.assertEqual(lm_model.unk_score_offset , -20.0 )
self.assertEqual(lm_model.score_boundary , A )
def a__ (self ) -> Optional[Any]:
"""simple docstring"""
_a = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_a = processor.decoder.model_container[processor.decoder._model_key]
_a = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute()
_a = os.listdir(A )
_a = ['''alphabet.json''', '''language_model''']
downloaded_decoder_files.sort()
expected_decoder_files.sort()
# test that only decoder relevant files from
# https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main
# are downloaded and none of the rest (e.g. README.md, ...)
self.assertListEqual(A , A )
def a__ (self ) -> Optional[Any]:
"""simple docstring"""
_a = snapshot_download('''hf-internal-testing/processor_with_lm''' )
_a = WavaVecaProcessorWithLM.from_pretrained(A )
_a = processor.decoder.model_container[processor.decoder._model_key]
_a = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute()
_a = os.listdir(A )
_a = os.listdir(A )
local_decoder_files.sort()
expected_decoder_files.sort()
# test that both decoder form hub and local files in cache are the same
self.assertListEqual(A , A )
def a__ (self ) -> Union[str, Any]:
"""simple docstring"""
_a = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_a = AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_a = floats_list((3, 1_000) )
_a = processor_wavaveca(A , return_tensors='''np''' )
_a = processor_auto(A , return_tensors='''np''' )
for key in input_wavaveca.keys():
self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 )
_a = self._get_dummy_logits()
_a = processor_wavaveca.batch_decode(A )
_a = processor_auto.batch_decode(A )
self.assertListEqual(decoded_wavaveca.text , decoded_auto.text )
def a__ (self ) -> List[str]:
"""simple docstring"""
_a = self.get_feature_extractor()
_a = self.get_tokenizer()
_a = self.get_decoder()
_a = WavaVecaProcessorWithLM(tokenizer=A , feature_extractor=A , decoder=A )
self.assertListEqual(
processor.model_input_names , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , )
@staticmethod
def a__ (A , A ) -> List[str]:
"""simple docstring"""
_a = [d[key] for d in offsets]
return retrieved_list
def a__ (self ) -> Optional[Any]:
"""simple docstring"""
_a = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_a = self._get_dummy_logits()[0]
_a = processor.decode(A , output_word_offsets=A )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) , 4 )
self.assertTrue('''text''' in outputs )
self.assertTrue('''word_offsets''' in outputs )
self.assertTrue(isinstance(A , A ) )
self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) ) , outputs.text )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''start_offset''' ) , [0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''end_offset''' ) , [1, 3, 5] )
def a__ (self ) -> Dict:
"""simple docstring"""
_a = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' )
_a = self._get_dummy_logits()
_a = processor.batch_decode(A , output_word_offsets=A )
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs.keys() ) , 4 )
self.assertTrue('''text''' in outputs )
self.assertTrue('''word_offsets''' in outputs )
self.assertTrue(isinstance(A , A ) )
self.assertListEqual(
[''' '''.join(self.get_from_offsets(A , '''word''' ) ) for o in outputs['''word_offsets''']] , outputs.text )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''start_offset''' ) , [0, 2, 4] )
self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''end_offset''' ) , [1, 3, 5] )
@slow
@require_torch
@require_torchaudio
def a__ (self ) -> Any:
"""simple docstring"""
import torch
_a = load_dataset('''common_voice''' , '''en''' , split='''train''' , streaming=A )
_a = ds.cast_column('''audio''' , datasets.Audio(sampling_rate=16_000 ) )
_a = iter(A )
_a = next(A )
_a = AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' )
_a = WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' )
# compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train
_a = processor(sample['''audio''']['''array'''] , return_tensors='''pt''' ).input_values
with torch.no_grad():
_a = model(A ).logits.cpu().numpy()
_a = processor.decode(logits[0] , output_word_offsets=A )
_a = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
_a = [
{
'''start_time''': d['''start_offset'''] * time_offset,
'''end_time''': d['''end_offset'''] * time_offset,
'''word''': d['''word'''],
}
for d in output['''word_offsets''']
]
_a = '''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL'''
# output words
self.assertEqual(''' '''.join(self.get_from_offsets(A , '''word''' ) ) , A )
self.assertEqual(''' '''.join(self.get_from_offsets(A , '''word''' ) ) , output.text )
# output times
_a = torch.tensor(self.get_from_offsets(A , '''start_time''' ) )
_a = torch.tensor(self.get_from_offsets(A , '''end_time''' ) )
# fmt: off
_a = torch.tensor([1.4199, 1.6599, 2.2599, 3.0, 3.24, 3.5999, 3.7999, 4.0999, 4.26, 4.94, 5.28, 5.6599, 5.78, 5.94, 6.32, 6.5399, 6.6599] )
_a = torch.tensor([1.5399, 1.8999, 2.9, 3.16, 3.5399, 3.72, 4.0199, 4.1799, 4.76, 5.1599, 5.5599, 5.6999, 5.86, 6.1999, 6.38, 6.6199, 6.94] )
# fmt: on
self.assertTrue(torch.allclose(A , A , atol=0.01 ) )
self.assertTrue(torch.allclose(A , A , atol=0.01 ) )
| 719 |
'''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.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool
lowercase_ = {
"Acehnese Arabic": "ace_Arab",
"Acehnese Latin": "ace_Latn",
"Mesopotamian Arabic": "acm_Arab",
"Ta'izzi-Adeni Arabic": "acq_Arab",
"Tunisian Arabic": "aeb_Arab",
"Afrikaans": "afr_Latn",
"South Levantine Arabic": "ajp_Arab",
"Akan": "aka_Latn",
"Amharic": "amh_Ethi",
"North Levantine Arabic": "apc_Arab",
"Modern Standard Arabic": "arb_Arab",
"Modern Standard Arabic Romanized": "arb_Latn",
"Najdi Arabic": "ars_Arab",
"Moroccan Arabic": "ary_Arab",
"Egyptian Arabic": "arz_Arab",
"Assamese": "asm_Beng",
"Asturian": "ast_Latn",
"Awadhi": "awa_Deva",
"Central Aymara": "ayr_Latn",
"South Azerbaijani": "azb_Arab",
"North Azerbaijani": "azj_Latn",
"Bashkir": "bak_Cyrl",
"Bambara": "bam_Latn",
"Balinese": "ban_Latn",
"Belarusian": "bel_Cyrl",
"Bemba": "bem_Latn",
"Bengali": "ben_Beng",
"Bhojpuri": "bho_Deva",
"Banjar Arabic": "bjn_Arab",
"Banjar Latin": "bjn_Latn",
"Standard Tibetan": "bod_Tibt",
"Bosnian": "bos_Latn",
"Buginese": "bug_Latn",
"Bulgarian": "bul_Cyrl",
"Catalan": "cat_Latn",
"Cebuano": "ceb_Latn",
"Czech": "ces_Latn",
"Chokwe": "cjk_Latn",
"Central Kurdish": "ckb_Arab",
"Crimean Tatar": "crh_Latn",
"Welsh": "cym_Latn",
"Danish": "dan_Latn",
"German": "deu_Latn",
"Southwestern Dinka": "dik_Latn",
"Dyula": "dyu_Latn",
"Dzongkha": "dzo_Tibt",
"Greek": "ell_Grek",
"English": "eng_Latn",
"Esperanto": "epo_Latn",
"Estonian": "est_Latn",
"Basque": "eus_Latn",
"Ewe": "ewe_Latn",
"Faroese": "fao_Latn",
"Fijian": "fij_Latn",
"Finnish": "fin_Latn",
"Fon": "fon_Latn",
"French": "fra_Latn",
"Friulian": "fur_Latn",
"Nigerian Fulfulde": "fuv_Latn",
"Scottish Gaelic": "gla_Latn",
"Irish": "gle_Latn",
"Galician": "glg_Latn",
"Guarani": "grn_Latn",
"Gujarati": "guj_Gujr",
"Haitian Creole": "hat_Latn",
"Hausa": "hau_Latn",
"Hebrew": "heb_Hebr",
"Hindi": "hin_Deva",
"Chhattisgarhi": "hne_Deva",
"Croatian": "hrv_Latn",
"Hungarian": "hun_Latn",
"Armenian": "hye_Armn",
"Igbo": "ibo_Latn",
"Ilocano": "ilo_Latn",
"Indonesian": "ind_Latn",
"Icelandic": "isl_Latn",
"Italian": "ita_Latn",
"Javanese": "jav_Latn",
"Japanese": "jpn_Jpan",
"Kabyle": "kab_Latn",
"Jingpho": "kac_Latn",
"Kamba": "kam_Latn",
"Kannada": "kan_Knda",
"Kashmiri Arabic": "kas_Arab",
"Kashmiri Devanagari": "kas_Deva",
"Georgian": "kat_Geor",
"Central Kanuri Arabic": "knc_Arab",
"Central Kanuri Latin": "knc_Latn",
"Kazakh": "kaz_Cyrl",
"Kabiyè": "kbp_Latn",
"Kabuverdianu": "kea_Latn",
"Khmer": "khm_Khmr",
"Kikuyu": "kik_Latn",
"Kinyarwanda": "kin_Latn",
"Kyrgyz": "kir_Cyrl",
"Kimbundu": "kmb_Latn",
"Northern Kurdish": "kmr_Latn",
"Kikongo": "kon_Latn",
"Korean": "kor_Hang",
"Lao": "lao_Laoo",
"Ligurian": "lij_Latn",
"Limburgish": "lim_Latn",
"Lingala": "lin_Latn",
"Lithuanian": "lit_Latn",
"Lombard": "lmo_Latn",
"Latgalian": "ltg_Latn",
"Luxembourgish": "ltz_Latn",
"Luba-Kasai": "lua_Latn",
"Ganda": "lug_Latn",
"Luo": "luo_Latn",
"Mizo": "lus_Latn",
"Standard Latvian": "lvs_Latn",
"Magahi": "mag_Deva",
"Maithili": "mai_Deva",
"Malayalam": "mal_Mlym",
"Marathi": "mar_Deva",
"Minangkabau Arabic ": "min_Arab",
"Minangkabau Latin": "min_Latn",
"Macedonian": "mkd_Cyrl",
"Plateau Malagasy": "plt_Latn",
"Maltese": "mlt_Latn",
"Meitei Bengali": "mni_Beng",
"Halh Mongolian": "khk_Cyrl",
"Mossi": "mos_Latn",
"Maori": "mri_Latn",
"Burmese": "mya_Mymr",
"Dutch": "nld_Latn",
"Norwegian Nynorsk": "nno_Latn",
"Norwegian Bokmål": "nob_Latn",
"Nepali": "npi_Deva",
"Northern Sotho": "nso_Latn",
"Nuer": "nus_Latn",
"Nyanja": "nya_Latn",
"Occitan": "oci_Latn",
"West Central Oromo": "gaz_Latn",
"Odia": "ory_Orya",
"Pangasinan": "pag_Latn",
"Eastern Panjabi": "pan_Guru",
"Papiamento": "pap_Latn",
"Western Persian": "pes_Arab",
"Polish": "pol_Latn",
"Portuguese": "por_Latn",
"Dari": "prs_Arab",
"Southern Pashto": "pbt_Arab",
"Ayacucho Quechua": "quy_Latn",
"Romanian": "ron_Latn",
"Rundi": "run_Latn",
"Russian": "rus_Cyrl",
"Sango": "sag_Latn",
"Sanskrit": "san_Deva",
"Santali": "sat_Olck",
"Sicilian": "scn_Latn",
"Shan": "shn_Mymr",
"Sinhala": "sin_Sinh",
"Slovak": "slk_Latn",
"Slovenian": "slv_Latn",
"Samoan": "smo_Latn",
"Shona": "sna_Latn",
"Sindhi": "snd_Arab",
"Somali": "som_Latn",
"Southern Sotho": "sot_Latn",
"Spanish": "spa_Latn",
"Tosk Albanian": "als_Latn",
"Sardinian": "srd_Latn",
"Serbian": "srp_Cyrl",
"Swati": "ssw_Latn",
"Sundanese": "sun_Latn",
"Swedish": "swe_Latn",
"Swahili": "swh_Latn",
"Silesian": "szl_Latn",
"Tamil": "tam_Taml",
"Tatar": "tat_Cyrl",
"Telugu": "tel_Telu",
"Tajik": "tgk_Cyrl",
"Tagalog": "tgl_Latn",
"Thai": "tha_Thai",
"Tigrinya": "tir_Ethi",
"Tamasheq Latin": "taq_Latn",
"Tamasheq Tifinagh": "taq_Tfng",
"Tok Pisin": "tpi_Latn",
"Tswana": "tsn_Latn",
"Tsonga": "tso_Latn",
"Turkmen": "tuk_Latn",
"Tumbuka": "tum_Latn",
"Turkish": "tur_Latn",
"Twi": "twi_Latn",
"Central Atlas Tamazight": "tzm_Tfng",
"Uyghur": "uig_Arab",
"Ukrainian": "ukr_Cyrl",
"Umbundu": "umb_Latn",
"Urdu": "urd_Arab",
"Northern Uzbek": "uzn_Latn",
"Venetian": "vec_Latn",
"Vietnamese": "vie_Latn",
"Waray": "war_Latn",
"Wolof": "wol_Latn",
"Xhosa": "xho_Latn",
"Eastern Yiddish": "ydd_Hebr",
"Yoruba": "yor_Latn",
"Yue Chinese": "yue_Hant",
"Chinese Simplified": "zho_Hans",
"Chinese Traditional": "zho_Hant",
"Standard Malay": "zsm_Latn",
"Zulu": "zul_Latn",
}
class __A ( A ):
'''simple docstring'''
__lowerCamelCase : Dict = 'facebook/nllb-200-distilled-600M'
__lowerCamelCase : Optional[Any] = (
'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should '
'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, '
'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in '
'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.'
)
__lowerCamelCase : Optional[int] = 'translator'
__lowerCamelCase : int = AutoTokenizer
__lowerCamelCase : List[Any] = AutoModelForSeqaSeqLM
__lowerCamelCase : int = LANGUAGE_CODES
__lowerCamelCase : Tuple = ['text', 'text', 'text']
__lowerCamelCase : Optional[Any] = ['text']
def a__ (self , A , A , A ) -> List[str]:
"""simple docstring"""
if src_lang not in self.lang_to_code:
raise ValueError(f'''{src_lang} is not a supported language.''' )
if tgt_lang not in self.lang_to_code:
raise ValueError(f'''{tgt_lang} is not a supported language.''' )
_a = self.lang_to_code[src_lang]
_a = self.lang_to_code[tgt_lang]
return self.pre_processor._build_translation_inputs(
A , return_tensors='''pt''' , src_lang=A , tgt_lang=A )
def a__ (self , A ) -> Optional[Any]:
"""simple docstring"""
return self.model.generate(**A )
def a__ (self , A ) -> List[str]:
"""simple docstring"""
return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=A )
| 352 | 0 |
import argparse
import dataclasses
import json
import logging
import os
import shutil
from typing import List, Optional
import datasets
from accelerate import Accelerator
from datasets import load_dataset
from finetuning import finetune
from tqdm.auto import tqdm
import transformers
from transformers import AutoConfig, set_seed
from transformers.trainer_utils import IntervalStrategy
lowercase = logging.getLogger(__name__)
lowercase = '''pytorch_model.bin'''
@dataclasses.dataclass
class __A:
SCREAMING_SNAKE_CASE = dataclasses.field(
metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models.'''} )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co.'''} , )
@dataclasses.dataclass
class __A:
SCREAMING_SNAKE_CASE = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the training data.'''} )
SCREAMING_SNAKE_CASE = dataclasses.field(metadata={'''help''': '''A csv or a json file containing the data to predict on.'''} )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''A csv or a json file containing the validation data.'''} )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''The name of the task to train on.'''} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''The list of labels for the task.'''} )
@dataclasses.dataclass
class __A:
SCREAMING_SNAKE_CASE = dataclasses.field(
metadata={'''help''': '''The output directory where the model predictions and checkpoints will be written.'''} )
SCREAMING_SNAKE_CASE = dataclasses.field(
default='''accuracy''' , metadata={'''help''': '''The evaluation metric used for the task.'''} )
SCREAMING_SNAKE_CASE = dataclasses.field(
default='''no''' , metadata={
'''help''': '''The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]'''
} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=1_0 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=0.0 , metadata={
'''help''': '''How much the specified evaluation metric must improve to satisfy early stopping conditions.'''
} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the confidence score.'''} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''Whether to filter the pseudo-labeled data based on the validation performance.'''} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''Whether to fine-tune on labeled data after pseudo training.'''} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=0.0 , metadata={'''help''': '''Confidence threshold for pseudo-labeled data filtering.'''} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=1_0_0 , metadata={'''help''': '''Number of evaluation calls with no improvement after which training will be stopped.'''} , )
SCREAMING_SNAKE_CASE = dataclasses.field(
default=UpperCAmelCase , metadata={'''help''': '''Random seed for initialization.'''} , )
def __lowerCAmelCase ( UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str ) -> List[str]:
lowerCamelCase_ = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 )
if args.do_filter_by_confidence:
lowerCamelCase_ = dataset.filter(lambda UpperCAmelCase__ : example["probability"] > args.confidence_threshold )
if args.do_filter_by_val_performance:
assert eval_result >= 0.0 and eval_result <= 1.0
lowerCamelCase_ = int(eval_result * len(UpperCAmelCase__ ) )
print(UpperCAmelCase__ )
lowerCamelCase_ = dataset.sort("""probability""" , reverse=UpperCAmelCase__ )
lowerCamelCase_ = dataset.select(range(UpperCAmelCase__ ) )
lowerCamelCase_ = dataset.remove_columns(["""label""", """probability"""] )
lowerCamelCase_ = dataset.rename_column("""prediction""" , """label""" )
lowerCamelCase_ = dataset.map(lambda UpperCAmelCase__ : {"label": idalabel[example["label"]]} )
lowerCamelCase_ = dataset.shuffle(seed=args.seed )
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , F'''train_pseudo.{args.data_file_extension}''' )
if args.data_file_extension == "csv":
dataset.to_csv(UpperCAmelCase__ , index=UpperCAmelCase__ )
else:
dataset.to_json(UpperCAmelCase__ )
def __lowerCAmelCase ( UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , **UpperCAmelCase__ : Dict ) -> Optional[int]:
lowerCamelCase_ = 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 , )
logger.info(accelerator.state )
# 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()
lowerCamelCase_ = STModelArguments(model_name_or_path=UpperCAmelCase__ )
lowerCamelCase_ = STDataArguments(train_file=UpperCAmelCase__ , infer_file=UpperCAmelCase__ )
lowerCamelCase_ = STTrainingArguments(output_dir=UpperCAmelCase__ )
lowerCamelCase_ = argparse.Namespace()
for arg_class in (model_args, data_args, training_args):
for key, value in vars(UpperCAmelCase__ ).items():
setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
for key, value in kwargs.items():
if hasattr(UpperCAmelCase__ , UpperCAmelCase__ ):
setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
# Sanity checks
lowerCamelCase_ = {}
lowerCamelCase_ = None
# You need to provide the training data and the data to predict on
assert args.train_file is not None
assert args.infer_file is not None
lowerCamelCase_ = args.train_file
lowerCamelCase_ = args.infer_file
if args.evaluation_strategy != IntervalStrategy.NO.value:
assert args.eval_file is not None
lowerCamelCase_ = args.eval_file
for key in data_files:
lowerCamelCase_ = data_files[key].split(""".""" )[-1]
assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.'''
if args.data_file_extension is None:
lowerCamelCase_ = extension
else:
assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.'''
assert (
args.eval_metric in datasets.list_metrics()
), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.'''
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed )
logger.info("""Creating the initial data directory for self-training...""" )
lowerCamelCase_ = F'''{args.output_dir}/self-train_iter-{{}}'''.format
lowerCamelCase_ = data_dir_format(0 )
if accelerator.is_main_process:
if args.output_dir is not None:
os.makedirs(args.output_dir , exist_ok=UpperCAmelCase__ )
os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ )
accelerator.wait_for_everyone()
lowerCamelCase_ = None
lowerCamelCase_ = None
lowerCamelCase_ = 0
lowerCamelCase_ = False
# Show the progress bar
lowerCamelCase_ = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process )
# Self-train
for iteration in range(0 , int(args.max_selftrain_iterations ) ):
lowerCamelCase_ = data_dir_format(UpperCAmelCase__ )
assert os.path.exists(UpperCAmelCase__ )
# Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for
# iteration > 0
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """stage-1""" )
lowerCamelCase_ = {
"""accelerator""": accelerator,
"""model_name_or_path""": args.model_name_or_path,
"""cache_dir""": args.cache_dir,
"""do_train""": True,
"""train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""],
"""do_eval""": True if args.eval_file is not None else False,
"""eval_file""": data_files["""eval"""],
"""do_predict""": True,
"""infer_file""": data_files["""infer"""],
"""task_name""": args.task_name,
"""label_list""": args.label_list,
"""output_dir""": current_output_dir,
"""eval_metric""": args.eval_metric,
"""evaluation_strategy""": args.evaluation_strategy,
"""early_stopping_patience""": args.early_stopping_patience,
"""early_stopping_threshold""": args.early_stopping_threshold,
"""seed""": args.seed,
}
# Add additional training arguments
for key, value in kwargs.items():
if key not in arguments_dict and not hasattr(UpperCAmelCase__ , UpperCAmelCase__ ):
arguments_dict.update({key: value} )
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """best-checkpoint""" , UpperCAmelCase__ )
if os.path.exists(UpperCAmelCase__ ):
logger.info(
"""Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , UpperCAmelCase__ , UpperCAmelCase__ , )
else:
logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , UpperCAmelCase__ )
finetune(**UpperCAmelCase__ )
accelerator.wait_for_everyone()
assert os.path.exists(UpperCAmelCase__ )
logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , UpperCAmelCase__ )
if iteration > 0 and args.finetune_on_labeled_data:
# Stage 2 (optional): fine-tuning on the original labeled data
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """best-checkpoint""" )
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """stage-2""" )
# Update arguments_dict
lowerCamelCase_ = model_path
lowerCamelCase_ = data_files["""train"""]
lowerCamelCase_ = current_output_dir
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """best-checkpoint""" , UpperCAmelCase__ )
if os.path.exists(UpperCAmelCase__ ):
logger.info(
"""Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , UpperCAmelCase__ , UpperCAmelCase__ , )
else:
logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , UpperCAmelCase__ )
finetune(**UpperCAmelCase__ )
accelerator.wait_for_everyone()
assert os.path.exists(UpperCAmelCase__ )
logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , UpperCAmelCase__ )
lowerCamelCase_ = iteration
lowerCamelCase_ = data_dir_format(iteration + 1 )
lowerCamelCase_ = AutoConfig.from_pretrained(os.path.join(UpperCAmelCase__ , """best-checkpoint""" ) )
lowerCamelCase_ = config.idalabel
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """eval_results_best-checkpoint.json""" )
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """test_results_best-checkpoint.json""" )
assert os.path.exists(UpperCAmelCase__ )
with open(UpperCAmelCase__ , """r""" ) as f:
lowerCamelCase_ = float(json.load(UpperCAmelCase__ )[args.eval_metric] )
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , """infer_output_best-checkpoint.csv""" )
assert os.path.exists(UpperCAmelCase__ )
# Loading the dataset from local csv or json files.
lowerCamelCase_ = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""]
lowerCamelCase_ = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""]
if accelerator.is_main_process:
os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ )
shutil.copy(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , F'''eval_results_iter-{iteration}.json''' ) )
if os.path.exists(UpperCAmelCase__ ):
shutil.copy(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , F'''test_results_iter-{iteration}.json''' ) )
create_pseudo_labeled_data(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
accelerator.wait_for_everyone()
lowerCamelCase_ = os.path.join(UpperCAmelCase__ , F'''train_pseudo.{args.data_file_extension}''' )
if args.evaluation_strategy != IntervalStrategy.NO.value:
lowerCamelCase_ = eval_result
if best_iteration is None:
lowerCamelCase_ = new_iteration
lowerCamelCase_ = new_eval_result
else:
if new_eval_result - best_eval_result > args.early_stopping_threshold:
lowerCamelCase_ = new_iteration
lowerCamelCase_ = new_eval_result
lowerCamelCase_ = 0
else:
if new_eval_result == best_eval_result:
lowerCamelCase_ = new_iteration
lowerCamelCase_ = new_eval_result
early_stopping_patience_counter += 1
if early_stopping_patience_counter >= args.early_stopping_patience:
lowerCamelCase_ = True
progress_bar.update(1 )
if should_training_stop:
break
if best_iteration is not None:
# Save the best iteration
logger.info("""Best iteration: %d""" , UpperCAmelCase__ )
logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCAmelCase__ )
accelerator.wait_for_everyone()
if accelerator.is_main_process:
shutil.copy(
os.path.join(UpperCAmelCase__ , F'''eval_results_iter-{iteration}.json''' ) , os.path.join(UpperCAmelCase__ , """eval_results_best-iteration.json""" ) , )
else:
# Assume that the last iteration is the best
logger.info("""Best iteration: %d""" , args.max_selftrain_iterations - 1 )
logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , UpperCAmelCase__ )
accelerator.wait_for_everyone()
if accelerator.is_main_process:
shutil.copy(
os.path.join(UpperCAmelCase__ , F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(UpperCAmelCase__ , """eval_results_best-iteration.json""" ) , )
| 272 |
import collections
import inspect
import unittest
from transformers import FocalNetConfig
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_backbone_common import BackboneTesterMixin
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 (
FocalNetBackbone,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetModel,
)
from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class __A:
def __init__( self : Tuple , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Optional[Any]=1_3 , __UpperCamelCase : str=3_2 , __UpperCamelCase : List[Any]=2 , __UpperCamelCase : Tuple=3 , __UpperCamelCase : List[Any]=1_6 , __UpperCamelCase : int=[3_2, 6_4, 1_2_8] , __UpperCamelCase : Tuple=[1, 2, 1] , __UpperCamelCase : List[Any]=[2, 2, 4] , __UpperCamelCase : int=2 , __UpperCamelCase : Tuple=2.0 , __UpperCamelCase : List[str]=True , __UpperCamelCase : List[Any]=0.0 , __UpperCamelCase : List[Any]=0.0 , __UpperCamelCase : Tuple=0.1 , __UpperCamelCase : Any="gelu" , __UpperCamelCase : int=False , __UpperCamelCase : List[Any]=True , __UpperCamelCase : Tuple=0.02 , __UpperCamelCase : Union[str, Any]=1E-5 , __UpperCamelCase : Dict=True , __UpperCamelCase : List[Any]=None , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : Optional[int]=1_0 , __UpperCamelCase : Union[str, Any]=8 , __UpperCamelCase : Optional[Any]=["stage1", "stage2"] , __UpperCamelCase : Tuple=[1, 2] , ):
lowerCamelCase_ = parent
lowerCamelCase_ = batch_size
lowerCamelCase_ = image_size
lowerCamelCase_ = patch_size
lowerCamelCase_ = num_channels
lowerCamelCase_ = embed_dim
lowerCamelCase_ = hidden_sizes
lowerCamelCase_ = depths
lowerCamelCase_ = num_heads
lowerCamelCase_ = window_size
lowerCamelCase_ = mlp_ratio
lowerCamelCase_ = qkv_bias
lowerCamelCase_ = hidden_dropout_prob
lowerCamelCase_ = attention_probs_dropout_prob
lowerCamelCase_ = drop_path_rate
lowerCamelCase_ = hidden_act
lowerCamelCase_ = use_absolute_embeddings
lowerCamelCase_ = patch_norm
lowerCamelCase_ = layer_norm_eps
lowerCamelCase_ = initializer_range
lowerCamelCase_ = is_training
lowerCamelCase_ = scope
lowerCamelCase_ = use_labels
lowerCamelCase_ = type_sequence_label_size
lowerCamelCase_ = encoder_stride
lowerCamelCase_ = out_features
lowerCamelCase_ = out_indices
def lowercase__ ( self : Tuple ):
lowerCamelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowerCamelCase_ = None
if self.use_labels:
lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowerCamelCase_ = self.get_config()
return config, pixel_values, labels
def lowercase__ ( self : Dict ):
return FocalNetConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , )
def lowercase__ ( self : List[str] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Tuple , __UpperCamelCase : Union[str, Any] ):
lowerCamelCase_ = FocalNetModel(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
lowerCamelCase_ = model(__UpperCamelCase )
lowerCamelCase_ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
lowerCamelCase_ = int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) )
def lowercase__ ( self : Optional[Any] , __UpperCamelCase : str , __UpperCamelCase : int , __UpperCamelCase : Union[str, Any] ):
lowerCamelCase_ = FocalNetBackbone(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
lowerCamelCase_ = model(__UpperCamelCase )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] )
# verify channels
self.parent.assertEqual(len(model.channels ) , len(config.out_features ) )
self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] )
# verify backbone works with out_features=None
lowerCamelCase_ = None
lowerCamelCase_ = FocalNetBackbone(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
lowerCamelCase_ = model(__UpperCamelCase )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) , 1 )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] )
# verify channels
self.parent.assertEqual(len(model.channels ) , 1 )
self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] )
def lowercase__ ( self : Optional[Any] , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : str , __UpperCamelCase : Any ):
lowerCamelCase_ = FocalNetForMaskedImageModeling(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
lowerCamelCase_ = model(__UpperCamelCase )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
lowerCamelCase_ = 1
lowerCamelCase_ = FocalNetForMaskedImageModeling(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
lowerCamelCase_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
lowerCamelCase_ = model(__UpperCamelCase )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def lowercase__ ( self : str , __UpperCamelCase : str , __UpperCamelCase : Optional[int] , __UpperCamelCase : Union[str, Any] ):
lowerCamelCase_ = self.type_sequence_label_size
lowerCamelCase_ = FocalNetForImageClassification(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
lowerCamelCase_ = model(__UpperCamelCase , labels=__UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
lowerCamelCase_ = 1
lowerCamelCase_ = FocalNetForImageClassification(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
lowerCamelCase_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
lowerCamelCase_ = model(__UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def lowercase__ ( self : Tuple ):
lowerCamelCase_ = self.prepare_config_and_inputs()
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = config_and_inputs
lowerCamelCase_ = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class __A( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ):
SCREAMING_SNAKE_CASE = (
(
FocalNetModel,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetBackbone,
)
if is_torch_available()
else ()
)
SCREAMING_SNAKE_CASE = (
{'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
if is_torch_available()
else {}
)
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
def lowercase__ ( self : str ):
lowerCamelCase_ = FocalNetModelTester(self )
lowerCamelCase_ = ConfigTester(self , config_class=__UpperCamelCase , embed_dim=3_7 , has_text_modality=__UpperCamelCase )
def lowercase__ ( self : Optional[Any] ):
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 lowercase__ ( self : Tuple ):
return
def lowercase__ ( self : Optional[int] ):
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCamelCase )
def lowercase__ ( self : Any ):
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*__UpperCamelCase )
def lowercase__ ( self : List[Any] ):
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCamelCase )
def lowercase__ ( self : List[Any] ):
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase )
@unittest.skip(reason="""FocalNet does not use inputs_embeds""" )
def lowercase__ ( self : str ):
pass
@unittest.skip(reason="""FocalNet does not use feedforward chunking""" )
def lowercase__ ( self : List[str] ):
pass
def lowercase__ ( self : Optional[int] ):
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes[:-1]:
lowerCamelCase_ = model_class(__UpperCamelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
lowerCamelCase_ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__UpperCamelCase , nn.Linear ) )
def lowercase__ ( self : Tuple ):
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes[:-1]:
lowerCamelCase_ = model_class(__UpperCamelCase )
lowerCamelCase_ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase_ = [*signature.parameters.keys()]
lowerCamelCase_ = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , __UpperCamelCase )
def lowercase__ ( self : Dict , __UpperCamelCase : Tuple , __UpperCamelCase : List[str] , __UpperCamelCase : str , __UpperCamelCase : Optional[Any] ):
lowerCamelCase_ = model_class(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
with torch.no_grad():
lowerCamelCase_ = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
lowerCamelCase_ = outputs.hidden_states
lowerCamelCase_ = getattr(
self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 )
self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase )
# FocalNet has a different seq_length
lowerCamelCase_ = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowerCamelCase_ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
lowerCamelCase_ = outputs.reshaped_hidden_states
self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase )
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = reshaped_hidden_states[0].shape
lowerCamelCase_ = (
reshaped_hidden_states[0].view(__UpperCamelCase , __UpperCamelCase , height * width ).permute(0 , 2 , 1 )
)
self.assertListEqual(
list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
def lowercase__ ( self : int ):
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase_ = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes[:-1]:
lowerCamelCase_ = True
self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase_ = True
self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
def lowercase__ ( self : List[str] ):
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase_ = 3
lowerCamelCase_ = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size , collections.abc.Iterable )
else (self.model_tester.image_size, self.model_tester.image_size)
)
lowerCamelCase_ = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
lowerCamelCase_ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
lowerCamelCase_ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes[:-1]:
lowerCamelCase_ = True
self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCamelCase_ = True
self.check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , (padded_height, padded_width) )
@slow
def lowercase__ ( self : Dict ):
for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCamelCase_ = FocalNetModel.from_pretrained(__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
def lowercase__ ( self : int ):
lowerCamelCase_ , lowerCamelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase_ = _config_zero_init(__UpperCamelCase )
for model_class in self.all_model_classes:
lowerCamelCase_ = model_class(config=__UpperCamelCase )
for name, param in model.named_parameters():
if "embeddings" not in name and 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''' , )
@require_vision
@require_torch
class __A( unittest.TestCase ):
@cached_property
def lowercase__ ( self : int ):
# TODO update organization
return AutoImageProcessor.from_pretrained("""microsoft/focalnet-tiny""" ) if is_vision_available() else None
@slow
def lowercase__ ( self : str ):
lowerCamelCase_ = FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny""" ).to(__UpperCamelCase )
lowerCamelCase_ = self.default_image_processor
lowerCamelCase_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
lowerCamelCase_ = image_processor(images=__UpperCamelCase , return_tensors="""pt""" ).to(__UpperCamelCase )
# forward pass
with torch.no_grad():
lowerCamelCase_ = model(**__UpperCamelCase )
# verify the logits
lowerCamelCase_ = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , __UpperCamelCase )
lowerCamelCase_ = torch.tensor([0.2166, -0.4368, 0.2191] ).to(__UpperCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCamelCase , atol=1E-4 ) )
self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 2_8_1 )
@require_torch
class __A( UpperCAmelCase , unittest.TestCase ):
SCREAMING_SNAKE_CASE = (FocalNetBackbone,) if is_torch_available() else ()
SCREAMING_SNAKE_CASE = FocalNetConfig
SCREAMING_SNAKE_CASE = False
def lowercase__ ( self : Any ):
lowerCamelCase_ = FocalNetModelTester(self )
| 272 | 1 |
'''simple docstring'''
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
_A : List[Any] =(3, 9, -11, 0, 7, 5, 1, -1)
_A : int =(4, 6, 2, 0, 8, 10, 3, -2)
@dataclass
class _lowercase :
a = 42
a = 42
class _lowercase :
def __init__( self: int , UpperCamelCase__: Iterable[int] ):
lowerCamelCase__ : Node | None = None
for i in sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ):
lowerCamelCase__ : Dict = Node(UpperCamelCase__ , self.head )
def __iter__( self: Optional[int] ):
lowerCamelCase__ : Dict = self.head
while node:
yield node.data
lowerCamelCase__ : List[str] = node.next_node
def __len__( self: Optional[Any] ):
return sum(1 for _ in self )
def __str__( self: Dict ):
return " -> ".join([str(UpperCamelCase__ ) for node in self] )
def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> SortedLinkedList:
return SortedLinkedList(list(UpperCamelCase ) + list(UpperCamelCase ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
_A : Any =SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| 631 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_A : Optional[Any] =logging.get_logger(__name__)
_A : Optional[int] ={
'''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''',
'''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''',
'''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''',
'''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''',
'''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''',
'''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''',
'''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''',
'''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''',
'''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''',
'''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''',
}
class _lowercase ( _lowercase ):
a = """rwkv"""
a = {"""max_position_embeddings""": """context_length"""}
def __init__( self: Tuple , UpperCamelCase__: Optional[Any]=50_277 , UpperCamelCase__: Union[str, Any]=1_024 , UpperCamelCase__: Tuple=4_096 , UpperCamelCase__: List[Any]=32 , UpperCamelCase__: Dict=None , UpperCamelCase__: Dict=None , UpperCamelCase__: int=1e-5 , UpperCamelCase__: Any=0 , UpperCamelCase__: str=0 , UpperCamelCase__: Union[str, Any]=6 , UpperCamelCase__: Optional[int]=False , UpperCamelCase__: Dict=True , **UpperCamelCase__: Dict , ):
lowerCamelCase__ : Dict = vocab_size
lowerCamelCase__ : Optional[Any] = context_length
lowerCamelCase__ : Optional[Any] = hidden_size
lowerCamelCase__ : Any = num_hidden_layers
lowerCamelCase__ : int = attention_hidden_size if attention_hidden_size is not None else hidden_size
lowerCamelCase__ : Union[str, Any] = intermediate_size if intermediate_size is not None else 4 * hidden_size
lowerCamelCase__ : List[str] = layer_norm_epsilon
lowerCamelCase__ : int = rescale_every
lowerCamelCase__ : Optional[int] = use_cache
lowerCamelCase__ : Dict = bos_token_id
lowerCamelCase__ : Any = eos_token_id
super().__init__(
tie_word_embeddings=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
| 631 | 1 |
'''simple docstring'''
import math
import os
from copy import deepcopy
import datasets
import evaluate
import torch
import transformers
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from accelerate import Accelerator
from accelerate.test_utils import RegressionDataset, RegressionModel
from accelerate.utils import is_tpu_available, set_seed
_UpperCamelCase : Optional[Any] = "true"
def snake_case ( snake_case : Tuple , snake_case : List[Any]=82 , snake_case : Optional[int]=16 ) -> Optional[Any]:
"""simple docstring"""
set_seed(42 )
lowerCAmelCase = RegressionModel()
lowerCAmelCase = deepcopy(snake_case )
lowerCAmelCase = RegressionDataset(length=snake_case )
lowerCAmelCase = DataLoader(snake_case , batch_size=snake_case )
model.to(accelerator.device )
lowerCAmelCase = accelerator.prepare(snake_case , snake_case )
return model, ddp_model, dataloader
def snake_case ( snake_case : Accelerator , snake_case : int=False ) -> Tuple:
"""simple docstring"""
lowerCAmelCase = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased' )
lowerCAmelCase = load_dataset('glue' , 'mrpc' , split='validation' )
def tokenize_function(snake_case : Dict ):
lowerCAmelCase = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=snake_case , max_length=snake_case )
return outputs
with accelerator.main_process_first():
lowerCAmelCase = dataset.map(
snake_case , batched=snake_case , remove_columns=['idx', 'sentence1', 'sentence2'] , )
lowerCAmelCase = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(snake_case : Union[str, Any] ):
if use_longest:
return tokenizer.pad(snake_case , padding='longest' , return_tensors='pt' )
return tokenizer.pad(snake_case , padding='max_length' , max_length=128 , return_tensors='pt' )
return DataLoader(snake_case , shuffle=snake_case , collate_fn=snake_case , batch_size=16 )
def snake_case ( snake_case : Union[str, Any] , snake_case : Union[str, Any] ) -> Tuple:
"""simple docstring"""
lowerCAmelCase = Accelerator(dispatch_batches=snake_case , split_batches=snake_case )
lowerCAmelCase = get_dataloader(snake_case , not dispatch_batches )
lowerCAmelCase = AutoModelForSequenceClassification.from_pretrained(
'hf-internal-testing/mrpc-bert-base-cased' , return_dict=snake_case )
lowerCAmelCase = accelerator.prepare(snake_case , snake_case )
return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator
def snake_case ( snake_case : Tuple , snake_case : List[str] , snake_case : List[str] ) -> Optional[Any]:
"""simple docstring"""
lowerCAmelCase = []
for batch in dataloader:
lowerCAmelCase = batch.values()
with torch.no_grad():
lowerCAmelCase = model(snake_case )
lowerCAmelCase = accelerator.gather_for_metrics((logit, target) )
logits_and_targets.append((logit, target) )
lowerCAmelCase = [], []
for logit, targ in logits_and_targets:
logits.append(snake_case )
targs.append(snake_case )
lowerCAmelCase = torch.cat(snake_case ), torch.cat(snake_case )
return logits, targs
def snake_case ( snake_case : Accelerator , snake_case : Union[str, Any]=82 , snake_case : List[str]=False , snake_case : Any=False , snake_case : Dict=16 ) -> int:
"""simple docstring"""
lowerCAmelCase = get_basic_setup(snake_case , snake_case , snake_case )
lowerCAmelCase = generate_predictions(snake_case , snake_case , snake_case )
assert (
len(snake_case ) == num_samples
), F'Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(snake_case )}'
def snake_case ( snake_case : bool = False , snake_case : bool = False ) -> List[str]:
"""simple docstring"""
lowerCAmelCase = evaluate.load('glue' , 'mrpc' )
lowerCAmelCase = get_mrpc_setup(snake_case , snake_case )
# First do baseline
lowerCAmelCase = setup['''no''']
model.to(snake_case )
model.eval()
for batch in dataloader:
batch.to(snake_case )
with torch.inference_mode():
lowerCAmelCase = model(**snake_case )
lowerCAmelCase = outputs.logits.argmax(dim=-1 )
metric.add_batch(predictions=snake_case , references=batch['labels'] )
lowerCAmelCase = metric.compute()
# Then do distributed
lowerCAmelCase = setup['''ddp''']
model.eval()
for batch in dataloader:
with torch.inference_mode():
lowerCAmelCase = model(**snake_case )
lowerCAmelCase = outputs.logits.argmax(dim=-1 )
lowerCAmelCase = batch['''labels''']
lowerCAmelCase = accelerator.gather_for_metrics((preds, references) )
metric.add_batch(predictions=snake_case , references=snake_case )
lowerCAmelCase = metric.compute()
for key in "accuracy f1".split():
assert math.isclose(
baseline[key] , distributed[key] ), F'Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n'
def snake_case ( ) -> Optional[int]:
"""simple docstring"""
lowerCAmelCase = Accelerator(split_batches=snake_case , dispatch_batches=snake_case )
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_warning()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# These are a bit slower so they should only be ran on the GPU or TPU
if torch.cuda.is_available() or is_tpu_available():
if accelerator.is_local_main_process:
print('**Testing gather_for_metrics**' )
for split_batches in [True, False]:
for dispatch_batches in [True, False]:
if accelerator.is_local_main_process:
print(F'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`' )
test_mrpc(snake_case , snake_case )
accelerator.state._reset_state()
if accelerator.is_local_main_process:
print('**Test torch metrics**' )
for split_batches in [True, False]:
for dispatch_batches in [True, False]:
lowerCAmelCase = Accelerator(split_batches=snake_case , dispatch_batches=snake_case )
if accelerator.is_local_main_process:
print(F'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99' )
test_torch_metrics(snake_case , 99 )
accelerator.state._reset_state()
if accelerator.is_local_main_process:
print('**Test last batch is not dropped when perfectly divisible**' )
lowerCAmelCase = Accelerator()
test_torch_metrics(snake_case , 512 )
accelerator.state._reset_state()
def snake_case ( snake_case : Any ) -> Any:
"""simple docstring"""
main()
if __name__ == "__main__":
main()
| 284 |
def lowercase_ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
while a != 0:
snake_case__, snake_case__ : int =b % a, a
return b
def lowercase_ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if gcd(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) != 1:
snake_case__ : List[str] =F'''mod inverse of {a!r} and {m!r} does not exist'''
raise ValueError(SCREAMING_SNAKE_CASE )
snake_case__, snake_case__, snake_case__ : Any =1, 0, a
snake_case__, snake_case__, snake_case__ : Any =0, 1, m
while va != 0:
snake_case__ : Dict =ua // va
snake_case__, snake_case__, snake_case__, snake_case__, snake_case__, snake_case__ : Dict =(ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m
| 381 | 0 |
from __future__ import annotations
def A ( lowercase__ : int , lowercase__ : int ) -> list[list[int]]:
UpperCamelCase__ :list[list[int]] = []
create_all_state(1 , lowercase__ , lowercase__ , [] , lowercase__ )
return result
def A ( lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : list[int] , lowercase__ : list[list[int]] , ) -> None:
if level == 0:
total_list.append(current_list[:] )
return
for i in range(lowercase__ , total_number - level + 2 ):
current_list.append(lowercase__ )
create_all_state(i + 1 , lowercase__ , level - 1 , lowercase__ , lowercase__ )
current_list.pop()
def A ( lowercase__ : list[list[int]] ) -> None:
for i in total_list:
print(*lowercase__ )
if __name__ == "__main__":
UpperCamelCase = 4
UpperCamelCase = 2
UpperCamelCase = generate_all_combinations(n, k)
print_all_state(total_list) | 383 |
import warnings
from ...utils import logging
from .image_processing_owlvit import OwlViTImageProcessor
UpperCamelCase = logging.get_logger(__name__)
class lowerCAmelCase_ ( lowercase ):
"""simple docstring"""
def __init__( self :Any , *lowerCamelCase__ :Union[str, Any] , **lowerCamelCase__ :int ):
warnings.warn(
"""The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"""
""" use OwlViTImageProcessor instead.""" , lowerCamelCase__ , )
super().__init__(*lowerCamelCase__ , **lowerCamelCase__ ) | 383 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowerCAmelCase_ = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ = [
'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST',
'ViTMSNModel',
'ViTMSNForImageClassification',
'ViTMSNPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vit_msn import (
VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST,
ViTMSNForImageClassification,
ViTMSNModel,
ViTMSNPreTrainedModel,
)
else:
import sys
lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__) | 217 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
lowerCAmelCase_ = logging.get_logger(__name__)
lowerCAmelCase_ = {
'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 _A ( _lowerCamelCase ):
_UpperCamelCase : Tuple = '''vit'''
def __init__( self : Dict , _A : str=768 , _A : List[str]=12 , _A : Union[str, Any]=12 , _A : Optional[Any]=3_072 , _A : Tuple="gelu" , _A : Any=0.0 , _A : Dict=0.0 , _A : Dict=0.02 , _A : Dict=1E-12 , _A : Tuple=224 , _A : int=16 , _A : Union[str, Any]=3 , _A : str=True , _A : Tuple=16 , **_A : int , ) -> int:
"""simple docstring"""
super().__init__(**_A )
lowercase : Optional[int] = hidden_size
lowercase : Any = num_hidden_layers
lowercase : Optional[int] = num_attention_heads
lowercase : Any = intermediate_size
lowercase : List[Any] = hidden_act
lowercase : Optional[int] = hidden_dropout_prob
lowercase : Dict = attention_probs_dropout_prob
lowercase : str = initializer_range
lowercase : str = layer_norm_eps
lowercase : List[Any] = image_size
lowercase : Tuple = patch_size
lowercase : Optional[int] = num_channels
lowercase : Tuple = qkv_bias
lowercase : Dict = encoder_stride
class _A ( _lowerCamelCase ):
_UpperCamelCase : Dict = version.parse('''1.11''' )
@property
def __a ( self : List[str] ) -> Mapping[str, Mapping[int, str]]:
"""simple docstring"""
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
] )
@property
def __a ( self : str ) -> float:
"""simple docstring"""
return 1E-4 | 217 | 1 |
from .imports import is_tqdm_available
if is_tqdm_available():
from tqdm.auto import tqdm as _tqdm
from ..state import PartialState
def A ( lowercase = True , *lowercase , **lowercase ) -> int:
'''simple docstring'''
if not is_tqdm_available():
raise ImportError('Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.' )
UpperCamelCase = False
if main_process_only:
UpperCamelCase = PartialState().local_process_index == 0
return _tqdm(*lowercase , **lowercase , disable=lowercase )
| 706 |
from random import shuffle
import tensorflow as tf
from numpy import array
def A ( lowercase , lowercase ) -> Optional[Any]:
'''simple docstring'''
UpperCamelCase = int(lowercase )
assert noofclusters < len(lowercase )
# Find out the dimensionality
UpperCamelCase = len(vectors[0] )
# Will help select random centroids from among the available vectors
UpperCamelCase = list(range(len(lowercase ) ) )
shuffle(lowercase )
# GRAPH OF COMPUTATION
# We initialize a new graph and set it as the default during each run
# of this algorithm. This ensures that as this function is called
# multiple times, the default graph doesn't keep getting crowded with
# unused ops and Variables from previous function calls.
UpperCamelCase = tf.Graph()
with graph.as_default():
# SESSION OF COMPUTATION
UpperCamelCase = tf.Session()
##CONSTRUCTING THE ELEMENTS OF COMPUTATION
##First lets ensure we have a Variable vector for each centroid,
##initialized to one of the vectors from the available data points
UpperCamelCase = [
tf.Variable(vectors[vector_indices[i]] ) for i in range(lowercase )
]
##These nodes will assign the centroid Variables the appropriate
##values
UpperCamelCase = tf.placeholder('float64' , [dim] )
UpperCamelCase = []
for centroid in centroids:
cent_assigns.append(tf.assign(lowercase , lowercase ) )
##Variables for cluster assignments of individual vectors(initialized
##to 0 at first)
UpperCamelCase = [tf.Variable(0 ) for i in range(len(lowercase ) )]
##These nodes will assign an assignment Variable the appropriate
##value
UpperCamelCase = tf.placeholder('int32' )
UpperCamelCase = []
for assignment in assignments:
cluster_assigns.append(tf.assign(lowercase , lowercase ) )
##Now lets construct the node that will compute the mean
# The placeholder for the input
UpperCamelCase = tf.placeholder('float' , [None, dim] )
# The Node/op takes the input and computes a mean along the 0th
# dimension, i.e. the list of input vectors
UpperCamelCase = tf.reduce_mean(lowercase , 0 )
##Node for computing Euclidean distances
# Placeholders for input
UpperCamelCase = tf.placeholder('float' , [dim] )
UpperCamelCase = tf.placeholder('float' , [dim] )
UpperCamelCase = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowercase , lowercase ) , 2 ) ) )
##This node will figure out which cluster to assign a vector to,
##based on Euclidean distances of the vector from the centroids.
# Placeholder for input
UpperCamelCase = tf.placeholder('float' , [noofclusters] )
UpperCamelCase = tf.argmin(lowercase , 0 )
##INITIALIZING STATE VARIABLES
##This will help initialization of all Variables defined with respect
##to the graph. The Variable-initializer should be defined after
##all the Variables have been constructed, so that each of them
##will be included in the initialization.
UpperCamelCase = tf.initialize_all_variables()
# Initialize all variables
sess.run(lowercase )
##CLUSTERING ITERATIONS
# Now perform the Expectation-Maximization steps of K-Means clustering
# iterations. To keep things simple, we will only do a set number of
# iterations, instead of using a Stopping Criterion.
UpperCamelCase = 100
for _ in range(lowercase ):
##EXPECTATION STEP
##Based on the centroid locations till last iteration, compute
##the _expected_ centroid assignments.
# Iterate over each vector
for vector_n in range(len(lowercase ) ):
UpperCamelCase = vectors[vector_n]
# Compute Euclidean distance between this vector and each
# centroid. Remember that this list cannot be named
#'centroid_distances', since that is the input to the
# cluster assignment node.
UpperCamelCase = [
sess.run(lowercase , feed_dict={va: vect, va: sess.run(lowercase )} )
for centroid in centroids
]
# Now use the cluster assignment node, with the distances
# as the input
UpperCamelCase = sess.run(
lowercase , feed_dict={centroid_distances: distances} )
# Now assign the value to the appropriate state variable
sess.run(
cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} )
##MAXIMIZATION STEP
# Based on the expected state computed from the Expectation Step,
# compute the locations of the centroids so as to maximize the
# overall objective of minimizing within-cluster Sum-of-Squares
for cluster_n in range(lowercase ):
# Collect all the vectors assigned to this cluster
UpperCamelCase = [
vectors[i]
for i in range(len(lowercase ) )
if sess.run(assignments[i] ) == cluster_n
]
# Compute new centroid location
UpperCamelCase = sess.run(
lowercase , feed_dict={mean_input: array(lowercase )} )
# Assign value to appropriate variable
sess.run(
cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} )
# Return centroids and assignments
UpperCamelCase = sess.run(lowercase )
UpperCamelCase = sess.run(lowercase )
return centroids, assignments
| 3 | 0 |
'''simple docstring'''
from .configuration_bert_masked import MaskedBertConfig
from .modeling_bert_masked import (
MaskedBertForMultipleChoice,
MaskedBertForQuestionAnswering,
MaskedBertForSequenceClassification,
MaskedBertForTokenClassification,
MaskedBertModel,
)
from .modules import * | 585 |
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available
from ...utils import OptionalDependencyNotAvailable
__UpperCAmelCase : Optional[Any] = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase : List[Any] = ["GPTNeoXTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase : Union[str, Any] = [
"GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST",
"GPTNeoXForCausalLM",
"GPTNeoXForQuestionAnswering",
"GPTNeoXForSequenceClassification",
"GPTNeoXForTokenClassification",
"GPTNeoXLayer",
"GPTNeoXModel",
"GPTNeoXPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox import (
GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXForCausalLM,
GPTNeoXForQuestionAnswering,
GPTNeoXForSequenceClassification,
GPTNeoXForTokenClassification,
GPTNeoXLayer,
GPTNeoXModel,
GPTNeoXPreTrainedModel,
)
else:
import sys
__UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) | 241 | 0 |
"""simple docstring"""
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class __snake_case ( __lowerCAmelCase ):
a__ = ["""image_processor""", """tokenizer"""]
a__ = """CLIPImageProcessor"""
a__ = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""")
def __init__( self , lowercase=None , lowercase=None , **lowercase) -> Dict:
'''simple docstring'''
a__: Optional[int] = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , UpperCAmelCase__ , )
a__: Dict = kwargs.pop('feature_extractor')
a__: Union[str, Any] = 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__(UpperCAmelCase__ , UpperCAmelCase__)
def __call__( self , lowercase=None , lowercase=None , lowercase=None , **lowercase) -> Dict:
'''simple docstring'''
if text is None and images is None:
raise ValueError('You have to specify either text or images. Both cannot be none.')
if text is not None:
a__: str = self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__)
if images is not None:
a__: List[str] = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__)
if text is not None and images is not None:
a__: List[str] = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**UpperCAmelCase__) , tensor_type=UpperCAmelCase__)
def lowerCamelCase_ ( self , *lowercase , **lowercase) -> Union[str, Any]:
'''simple docstring'''
return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__)
def lowerCamelCase_ ( self , *lowercase , **lowercase) -> str:
'''simple docstring'''
return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__)
@property
def lowerCamelCase_ ( self) -> List[str]:
'''simple docstring'''
a__: List[str] = self.tokenizer.model_input_names
a__: List[str] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 721 | """simple docstring"""
import re
def __a ( _SCREAMING_SNAKE_CASE ) ->list:
return [char.split() for char in re.split(r'[^ a-z A-Z 0-9 \s]' , str_ )]
def __a ( _SCREAMING_SNAKE_CASE ) ->str:
a__: int = split_input(str_ )
return "".join(
[''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] )
def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str:
try:
a__: List[str] = split_input(_SCREAMING_SNAKE_CASE )
if upper:
a__: Optional[int] = ''.join(
[
separator.join([char.upper() for char in sub_str] )
for sub_str in string_split
] )
else:
a__: Optional[Any] = ''.join(
[
separator.join([char.lower() for char in sub_str] )
for sub_str in string_split
] )
return res_str
except IndexError:
return "not valid string"
def __a ( _SCREAMING_SNAKE_CASE ) ->str:
return to_simple_case(_SCREAMING_SNAKE_CASE )
def __a ( _SCREAMING_SNAKE_CASE ) ->str:
try:
a__: Union[str, Any] = to_simple_case(_SCREAMING_SNAKE_CASE )
return res_str[0].lower() + res_str[1:]
except IndexError:
return "not valid string"
def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str:
return to_complex_case(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , '_' )
def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->str:
return to_complex_case(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , '-' )
if __name__ == "__main__":
__import__('doctest').testmod()
| 217 | 0 |
import unittest
import torch
from torch import nn
from diffusers.models.activations import get_activation
class lowerCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
def A ( self ) -> List[str]:
'''simple docstring'''
__lowercase = get_activation('''swish''' )
self.assertIsInstance(snake_case_ , nn.SiLU )
self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 )
def A ( self ) -> str:
'''simple docstring'''
__lowercase = get_activation('''silu''' )
self.assertIsInstance(snake_case_ , nn.SiLU )
self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 )
def A ( self ) -> int:
'''simple docstring'''
__lowercase = get_activation('''mish''' )
self.assertIsInstance(snake_case_ , nn.Mish )
self.assertEqual(act(torch.tensor(-2_0_0 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 )
def A ( self ) -> List[Any]:
'''simple docstring'''
__lowercase = get_activation('''gelu''' )
self.assertIsInstance(snake_case_ , nn.GELU )
self.assertEqual(act(torch.tensor(-1_0_0 , dtype=torch.floataa ) ).item() , 0 )
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 )
self.assertEqual(act(torch.tensor(2_0 , dtype=torch.floataa ) ).item() , 2_0 )
| 639 |
from __future__ import annotations
class lowerCamelCase_ :
'''simple docstring'''
def __init__( self , snake_case_ ) -> None:
'''simple docstring'''
__lowercase = order
# a_{0} ... a_{k}
__lowercase = [1.0] + [0.0] * order
# b_{0} ... b_{k}
__lowercase = [1.0] + [0.0] * order
# x[n-1] ... x[n-k]
__lowercase = [0.0] * self.order
# y[n-1] ... y[n-k]
__lowercase = [0.0] * self.order
def A ( self , snake_case_ , snake_case_ ) -> None:
'''simple docstring'''
if len(snake_case_ ) < self.order:
__lowercase = [1.0, *a_coeffs]
if len(snake_case_ ) != self.order + 1:
__lowercase = (
F'Expected a_coeffs to have {self.order + 1} elements '
F'for {self.order}-order filter, got {len(snake_case_ )}'
)
raise ValueError(snake_case_ )
if len(snake_case_ ) != self.order + 1:
__lowercase = (
F'Expected b_coeffs to have {self.order + 1} elements '
F'for {self.order}-order filter, got {len(snake_case_ )}'
)
raise ValueError(snake_case_ )
__lowercase = a_coeffs
__lowercase = b_coeffs
def A ( self , snake_case_ ) -> float:
'''simple docstring'''
__lowercase = 0.0
# Start at index 1 and do index 0 at the end.
for i in range(1 , self.order + 1 ):
result += (
self.b_coeffs[i] * self.input_history[i - 1]
- self.a_coeffs[i] * self.output_history[i - 1]
)
__lowercase = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0]
__lowercase = self.input_history[:-1]
__lowercase = self.output_history[:-1]
__lowercase = sample
__lowercase = result
return result
| 639 | 1 |
from typing import List
import jiwer
import jiwer.transforms as tr
from packaging import version
import datasets
from datasets.config import PY_VERSION
if PY_VERSION < version.parse('''3.8'''):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
UpperCAmelCase = ''''''
if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):
class A_ ( tr.AbstractTransform ):
'''simple docstring'''
def __init__( self , snake_case = " " ):
lowercase = sentence_delimiter
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
return list(snake_case )
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
lowercase = []
for sent_idx, sentence in enumerate(snake_case ):
chars.extend(self.process_string(snake_case ) )
if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(snake_case ) - 1:
chars.append(self.sentence_delimiter )
return chars
UpperCAmelCase = tr.Compose(
[tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
)
else:
UpperCAmelCase = tr.Compose(
[
tr.RemoveMultipleSpaces(),
tr.Strip(),
tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
tr.ReduceToListOfListOfChars(),
]
)
UpperCAmelCase = '''\
@inproceedings{inproceedings,
author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
year = {2004},
month = {01},
pages = {},
title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''
UpperCAmelCase = '''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.
CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.
Character error rate can be computed as:
CER = (S + D + I) / N = (S + D + I) / (S + D + C)
where
S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).
CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''
UpperCAmelCase = '''
Computes CER score of transcribed segments against references.
Args:
references: list of references for each speech input.
predictions: list of transcribtions to score.
concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
(float): the character error rate
Examples:
>>> predictions = ["this is the prediction", "there is an other sample"]
>>> references = ["this is the reference", "there is another one"]
>>> cer = datasets.load_metric("cer")
>>> cer_score = cer.compute(predictions=predictions, references=references)
>>> print(cer_score)
0.34146341463414637
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class A_ ( datasets.Metric ):
'''simple docstring'''
def SCREAMING_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.Value('string' , id='sequence' ),
} ) , codebase_urls=['https://github.com/jitsi/jiwer/'] , reference_urls=[
'https://en.wikipedia.org/wiki/Word_error_rate',
'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates',
] , )
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case=False ):
if concatenate_texts:
return jiwer.compute_measures(
snake_case , snake_case , truth_transform=snake_case , hypothesis_transform=snake_case , )["wer"]
lowercase = 0
lowercase = 0
for prediction, reference in zip(snake_case , snake_case ):
lowercase = jiwer.compute_measures(
snake_case , snake_case , truth_transform=snake_case , hypothesis_transform=snake_case , )
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total
| 565 |
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ):
lowercase = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
lowercase = set()
return any(
node not in visited and depth_first_search(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
for node in graph )
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
visited.add(__SCREAMING_SNAKE_CASE )
rec_stk.add(__SCREAMING_SNAKE_CASE )
for node in graph[vertex]:
if node not in visited:
if depth_first_search(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(__SCREAMING_SNAKE_CASE )
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| 565 | 1 |
import argparse
import torch
from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def A__ ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Tuple ) -> int:
"""simple docstring"""
if gpta_config_file == "":
_UpperCAmelCase = GPTaConfig()
else:
_UpperCAmelCase = GPTaConfig.from_json_file(SCREAMING_SNAKE_CASE_ )
_UpperCAmelCase = GPTaModel(SCREAMING_SNAKE_CASE_ )
# Load weights from numpy
load_tf_weights_in_gpta(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save pytorch-model
_UpperCAmelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
_UpperCAmelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict() , SCREAMING_SNAKE_CASE_ )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
UpperCAmelCase_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--gpt2_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
parser.add_argument(
"--gpt2_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained OpenAI model. \n"
"This specifies the model architecture."
),
)
UpperCAmelCase_ = parser.parse_args()
convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path) | 32 |
# Usage:
# ./gen-card-facebook-wmt19.py
import os
from pathlib import Path
def SCREAMING_SNAKE_CASE_ ( __A : List[str] , __A : Any , __A : Union[str, Any] ) -> Tuple:
"""simple docstring"""
a_ : str = {
'en': 'Machine learning is great, isn\'t it?',
'ru': 'Машинное обучение - это здорово, не так ли?',
'de': 'Maschinelles Lernen ist großartig, oder?',
}
# BLUE scores as follows:
# "pair": [fairseq, transformers]
a_ : str = {
'ru-en': ['[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)', '39.20'],
'en-ru': ['[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)', '33.47'],
'en-de': ['[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)', '42.83'],
'de-en': ['[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)', '41.35'],
}
a_ : Optional[int] = F"""{src_lang}-{tgt_lang}"""
a_ : str = F"""
---
language:
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt19
- facebook
license: apache-2.0
datasets:
- wmt19
metrics:
- bleu
---
# FSMT
## Model description
This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.
For more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).
The abbreviation FSMT stands for FairSeqMachineTranslation
All four models are available:
* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)
* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)
* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)
* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)
## Intended uses & limitations
#### How to use
```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"
tokenizer = FSMTTokenizer.from_pretrained(mname)
model = FSMTForConditionalGeneration.from_pretrained(mname)
input = \"{texts[src_lang]}\"
input_ids = tokenizer.encode(input, return_tensors=\"pt\")
outputs = model.generate(input_ids)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(decoded) # {texts[tgt_lang]}
```
#### Limitations and bias
- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)
## Training data
Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).
## Eval results
pair | fairseq | transformers
-------|---------|----------
{pair} | {scores[pair][0]} | {scores[pair][1]}
The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:
- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).
- re-ranking
The score was calculated using this code:
```bash
git clone https://github.com/huggingface/transformers
cd transformers
export PAIR={pair}
export DATA_DIR=data/$PAIR
export SAVE_DIR=data/$PAIR
export BS=8
export NUM_BEAMS=15
mkdir -p $DATA_DIR
sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
echo $PAIR
PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
```
note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.
## Data Sources
- [training, etc.](http://www.statmt.org/wmt19/)
- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)
### BibTeX entry and citation info
```bibtex
@inproceedings{{...,
year={{2020}},
title={{Facebook FAIR's WMT19 News Translation Task Submission}},
author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},
booktitle={{Proc. of WMT}},
}}
```
## TODO
- port model ensemble (fairseq uses 4 model checkpoints)
"""
os.makedirs(__A , exist_ok=__A )
a_ : Optional[int] = os.path.join(__A , 'README.md' )
print(F"""Generating {path}""" )
with open(__A , 'w' , encoding='utf-8' ) as f:
f.write(__A )
# make sure we are under the root of the project
UpperCAmelCase_ : List[str] = Path(__file__).resolve().parent.parent.parent
UpperCAmelCase_ : Union[str, Any] = repo_dir / 'model_cards'
for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = model_name.split('-')
UpperCAmelCase_ : Any = model_cards_dir / 'facebook' / model_name
write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
| 570 | 0 |
'''simple docstring'''
from __future__ import annotations
def UpperCamelCase__ ( _lowercase : Tuple , _lowercase : Tuple = None , _lowercase : str = None ) -> Any:
if start is None:
__UpperCAmelCase: List[Any] = 0
if end is None:
__UpperCAmelCase: str = len(_snake_case ) - 1
if start >= end:
return
__UpperCAmelCase: Tuple = (start + end) // 2
slowsort(_snake_case , _snake_case , _snake_case )
slowsort(_snake_case , mid + 1 , _snake_case )
if sequence[end] < sequence[mid]:
__UpperCAmelCase, __UpperCAmelCase: Optional[int] = sequence[mid], sequence[end]
slowsort(_snake_case , _snake_case , end - 1 )
if __name__ == "__main__":
from doctest import testmod
testmod()
| 711 | '''simple docstring'''
from __future__ import annotations
import time
import numpy as np
SCREAMING_SNAKE_CASE_ = [8, 5, 9, 7]
SCREAMING_SNAKE_CASE_ = [
[2, 0, 1, 1],
[0, 1, 2, 1],
[4, 0, 0, 3],
[0, 2, 1, 0],
[1, 0, 3, 0],
]
SCREAMING_SNAKE_CASE_ = [
[3, 2, 1, 4],
[0, 2, 5, 2],
[5, 1, 0, 5],
[1, 5, 3, 0],
[3, 0, 3, 3],
]
class a :
"""simple docstring"""
def __init__( self , snake_case_ , snake_case_ , snake_case_ , ):
'''simple docstring'''
__UpperCAmelCase: str = claim_vector
__UpperCAmelCase: Optional[Any] = allocated_resources_table
__UpperCAmelCase: List[str] = maximum_claim_table
def lowercase_ ( self ):
'''simple docstring'''
return [
sum(p_item[i] for p_item in self.__allocated_resources_table )
for i in range(len(self.__allocated_resources_table[0] ) )
]
def lowercase_ ( self ):
'''simple docstring'''
return np.array(self.__claim_vector ) - np.array(
self.__processes_resource_summation() )
def lowercase_ ( self ):
'''simple docstring'''
return [
list(np.array(self.__maximum_claim_table[i] ) - np.array(snake_case_ ) )
for i, allocated_resource in enumerate(self.__allocated_resources_table )
]
def lowercase_ ( self ):
'''simple docstring'''
return {self.__need().index(snake_case_ ): i for i in self.__need()}
def lowercase_ ( self , **snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Dict = self.__need()
__UpperCAmelCase: Optional[Any] = self.__allocated_resources_table
__UpperCAmelCase: int = self.__available_resources()
__UpperCAmelCase: List[Any] = self.__need_index_manager()
for kw, val in kwargs.items():
if kw and val is True:
self.__pretty_data()
print("""_""" * 50 + """\n""" )
while need_list:
__UpperCAmelCase: Any = False
for each_need in need_list:
__UpperCAmelCase: Any = True
for index, need in enumerate(snake_case_ ):
if need > available_resources[index]:
__UpperCAmelCase: Tuple = False
break
if execution:
__UpperCAmelCase: Optional[int] = True
# get the original index of the process from ind_ctrl db
for original_need_index, need_clone in need_index_manager.items():
if each_need == need_clone:
__UpperCAmelCase: Tuple = original_need_index
print(F'''Process {process_number + 1} is executing.''' )
# remove the process run from stack
need_list.remove(snake_case_ )
# update available/freed resources stack
__UpperCAmelCase: Dict = np.array(snake_case_ ) + np.array(
alloc_resources_table[process_number] )
print(
"""Updated available resource stack for processes: """
+ """ """.join([str(snake_case_ ) for x in available_resources] ) )
break
if safe:
print("""The process is in a safe state.\n""" )
else:
print("""System in unsafe state. Aborting...\n""" )
break
def lowercase_ ( self ):
'''simple docstring'''
print(""" """ * 9 + """Allocated Resource Table""" )
for item in self.__allocated_resources_table:
print(
F'''P{self.__allocated_resources_table.index(snake_case_ ) + 1}'''
+ """ """.join(F'''{it:>8}''' for it in item )
+ """\n""" )
print(""" """ * 9 + """System Resource Table""" )
for item in self.__maximum_claim_table:
print(
F'''P{self.__maximum_claim_table.index(snake_case_ ) + 1}'''
+ """ """.join(F'''{it:>8}''' for it in item )
+ """\n""" )
print(
"""Current Usage by Active Processes: """
+ """ """.join(str(snake_case_ ) for x in self.__claim_vector ) )
print(
"""Initial Available Resources: """
+ """ """.join(str(snake_case_ ) for x in self.__available_resources() ) )
time.sleep(1 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 466 | 0 |
'''simple docstring'''
from typing import Optional
import pyspark
from .. import Features, NamedSplit
from ..download import DownloadMode
from ..packaged_modules.spark.spark import Spark
from .abc import AbstractDatasetReader
class SCREAMING_SNAKE_CASE__ ( snake_case_):
def __init__( self , A_ , A_ = None , A_ = None , A_ = True , A_ = None , A_ = False , A_ = None , A_ = True , A_ = "arrow" , **A_ , )-> str:
'''simple docstring'''
super().__init__(
split=A_ , features=A_ , cache_dir=A_ , keep_in_memory=A_ , streaming=A_ , **A_ , )
UpperCamelCase = load_from_cache_file
UpperCamelCase = file_format
UpperCamelCase = Spark(
df=A_ , features=A_ , cache_dir=A_ , working_dir=A_ , **A_ , )
def UpperCAmelCase_ ( self )-> Optional[Any]:
'''simple docstring'''
if self.streaming:
return self.builder.as_streaming_dataset(split=self.split )
UpperCamelCase = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD
self.builder.download_and_prepare(
download_mode=A_ , file_format=self._file_format , )
return self.builder.as_dataset(split=self.split )
| 3 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DonutImageProcessor
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase):
def __init__( self , A_ , A_=7 , A_=3 , A_=18 , A_=30 , A_=400 , A_=True , A_=None , A_=True , A_=False , A_=True , A_=True , A_=[0.5, 0.5, 0.5] , A_=[0.5, 0.5, 0.5] , )-> Dict:
'''simple docstring'''
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = num_channels
UpperCamelCase = image_size
UpperCamelCase = min_resolution
UpperCamelCase = max_resolution
UpperCamelCase = do_resize
UpperCamelCase = size if size is not None else {'height': 18, 'width': 20}
UpperCamelCase = do_thumbnail
UpperCamelCase = do_align_axis
UpperCamelCase = do_pad
UpperCamelCase = do_normalize
UpperCamelCase = image_mean
UpperCamelCase = image_std
def UpperCAmelCase_ ( self )-> List[Any]:
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_thumbnail": self.do_thumbnail,
"do_align_long_axis": self.do_align_axis,
"do_pad": self.do_pad,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__ ( snake_case_ , unittest.TestCase):
lowerCAmelCase_ = DonutImageProcessor if is_vision_available() else None
def UpperCAmelCase_ ( self )-> str:
'''simple docstring'''
UpperCamelCase = DonutImageProcessingTester(self )
@property
def UpperCAmelCase_ ( self )-> str:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(A_ , 'do_resize' ) )
self.assertTrue(hasattr(A_ , 'size' ) )
self.assertTrue(hasattr(A_ , 'do_thumbnail' ) )
self.assertTrue(hasattr(A_ , 'do_align_long_axis' ) )
self.assertTrue(hasattr(A_ , 'do_pad' ) )
self.assertTrue(hasattr(A_ , 'do_normalize' ) )
self.assertTrue(hasattr(A_ , 'image_mean' ) )
self.assertTrue(hasattr(A_ , 'image_std' ) )
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'height': 18, 'width': 20} )
UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'height': 42, 'width': 42} )
# Previous config had dimensions in (width, height) order
UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) )
self.assertEqual(image_processor.size , {'height': 84, 'width': 42} )
def UpperCAmelCase_ ( self )-> Tuple:
'''simple docstring'''
pass
@is_flaky()
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ )
for image in image_inputs:
self.assertIsInstance(A_ , Image.Image )
# Test not batched input
UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
UpperCamelCase = image_processing(A_ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
@is_flaky()
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , numpify=A_ )
for image in image_inputs:
self.assertIsInstance(A_ , np.ndarray )
# Test not batched input
UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
UpperCamelCase = image_processing(A_ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
@is_flaky()
def UpperCAmelCase_ ( self )-> Dict:
'''simple docstring'''
UpperCamelCase = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , torchify=A_ )
for image in image_inputs:
self.assertIsInstance(A_ , torch.Tensor )
# Test not batched input
UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
# Test batched
UpperCamelCase = image_processing(A_ , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size['height'],
self.image_processor_tester.size['width'],
) , )
| 3 | 1 |
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING
import numpy as np
import pyarrow as pa
from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
if TYPE_CHECKING:
import torch
class __magic_name__ ( TensorFormatter[Mapping, "torch.Tensor", Mapping] ):
"""simple docstring"""
def __init__( self , a__=None , **a__ ):
super().__init__(features=a__ )
_lowerCamelCase = torch_tensor_kwargs
import torch # noqa import torch at initialization
def _UpperCAmelCase ( self , a__ ):
import torch
if isinstance(a__ , a__ ) and column:
if all(
isinstance(a__ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype
for x in column ):
return torch.stack(a__ )
return column
def _UpperCAmelCase ( self , a__ ):
import torch
if isinstance(a__ , (str, bytes, type(a__ )) ):
return value
elif isinstance(a__ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ):
return value.tolist()
_lowerCamelCase = {}
if isinstance(a__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ):
_lowerCamelCase = {"dtype": torch.intaa}
elif isinstance(a__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ):
_lowerCamelCase = {"dtype": torch.floataa}
elif config.PIL_AVAILABLE and "PIL" in sys.modules:
import PIL.Image
if isinstance(a__ , PIL.Image.Image ):
_lowerCamelCase = np.asarray(a__ )
return torch.tensor(a__ , **{**default_dtype, **self.torch_tensor_kwargs} )
def _UpperCAmelCase ( self , a__ ):
import torch
# support for torch, tf, jax etc.
if hasattr(a__ , '''__array__''' ) and not isinstance(a__ , torch.Tensor ):
_lowerCamelCase = data_struct.__array__()
# support for nested types like struct of list of struct
if isinstance(a__ , np.ndarray ):
if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects
return self._consolidate([self.recursive_tensorize(a__ ) for substruct in data_struct] )
elif isinstance(a__ , (list, tuple) ):
return self._consolidate([self.recursive_tensorize(a__ ) for substruct in data_struct] )
return self._tensorize(a__ )
def _UpperCAmelCase ( self , a__ ):
return map_nested(self._recursive_tensorize , a__ , map_list=a__ )
def _UpperCAmelCase ( self , a__ ):
_lowerCamelCase = self.numpy_arrow_extractor().extract_row(a__ )
_lowerCamelCase = self.python_features_decoder.decode_row(a__ )
return self.recursive_tensorize(a__ )
def _UpperCAmelCase ( self , a__ ):
_lowerCamelCase = self.numpy_arrow_extractor().extract_column(a__ )
_lowerCamelCase = self.python_features_decoder.decode_column(a__ , pa_table.column_names[0] )
_lowerCamelCase = self.recursive_tensorize(a__ )
_lowerCamelCase = self._consolidate(a__ )
return column
def _UpperCAmelCase ( self , a__ ):
_lowerCamelCase = self.numpy_arrow_extractor().extract_batch(a__ )
_lowerCamelCase = self.python_features_decoder.decode_batch(a__ )
_lowerCamelCase = self.recursive_tensorize(a__ )
for column_name in batch:
_lowerCamelCase = self._consolidate(batch[column_name] )
return batch
| 715 |
from __future__ import annotations
from collections.abc import MutableSequence
class __magic_name__ :
"""simple docstring"""
def __init__( self , a__ , a__ ):
if len(a__ ) != degree + 1:
raise ValueError(
'''The number of coefficients should be equal to the degree + 1.''' )
_lowerCamelCase = list(a__ )
_lowerCamelCase = degree
def __add__( self , a__ ):
if self.degree > polynomial_a.degree:
_lowerCamelCase = self.coefficients[:]
for i in range(polynomial_a.degree + 1 ):
coefficients[i] += polynomial_a.coefficients[i]
return Polynomial(self.degree , a__ )
else:
_lowerCamelCase = polynomial_a.coefficients[:]
for i in range(self.degree + 1 ):
coefficients[i] += self.coefficients[i]
return Polynomial(polynomial_a.degree , a__ )
def __sub__( self , a__ ):
return self + polynomial_a * Polynomial(0 , [-1] )
def __neg__( self ):
return Polynomial(self.degree , [-c for c in self.coefficients] )
def __mul__( self , a__ ):
_lowerCamelCase = [0] * (self.degree + polynomial_a.degree + 1)
for i in range(self.degree + 1 ):
for j in range(polynomial_a.degree + 1 ):
coefficients[i + j] += (
self.coefficients[i] * polynomial_a.coefficients[j]
)
return Polynomial(self.degree + polynomial_a.degree , a__ )
def _UpperCAmelCase ( self , a__ ):
_lowerCamelCase = 0
for i in range(self.degree + 1 ):
result += self.coefficients[i] * (substitution**i)
return result
def __str__( self ):
_lowerCamelCase = ''''''
for i in range(self.degree , -1 , -1 ):
if self.coefficients[i] == 0:
continue
elif self.coefficients[i] > 0:
if polynomial:
polynomial += " + "
else:
polynomial += " - "
if i == 0:
polynomial += str(abs(self.coefficients[i] ) )
elif i == 1:
polynomial += str(abs(self.coefficients[i] ) ) + "x"
else:
polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(a__ )
return polynomial
def __repr__( self ):
return self.__str__()
def _UpperCAmelCase ( self ):
_lowerCamelCase = [0] * self.degree
for i in range(self.degree ):
_lowerCamelCase = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1 , a__ )
def _UpperCAmelCase ( self , a__ = 0 ):
_lowerCamelCase = [0] * (self.degree + 2)
_lowerCamelCase = constant
for i in range(self.degree + 1 ):
_lowerCamelCase = self.coefficients[i] / (i + 1)
return Polynomial(self.degree + 1 , a__ )
def __eq__( self , a__ ):
if not isinstance(a__ , a__ ):
return False
if self.degree != polynomial_a.degree:
return False
for i in range(self.degree + 1 ):
if self.coefficients[i] != polynomial_a.coefficients[i]:
return False
return True
def __ne__( self , a__ ):
return not self.__eq__(a__ )
| 297 | 0 |
"""simple docstring"""
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path
import torch_xla.distributed.xla_multiprocessing as xmp
def __snake_case ( ) -> List[str]:
lowercase : str = ArgumentParser(
description=(
"""PyTorch TPU distributed training launch """
"""helper utility that will spawn up """
"""multiple distributed processes"""
) )
# Optional arguments for the launch helper
parser.add_argument("""--num_cores""" ,type=snake_case_ ,default=1 ,help="""Number of TPU cores to use (1 or 8).""" )
# positional
parser.add_argument(
"""training_script""" ,type=snake_case_ ,help=(
"""The full path to the single TPU training """
"""program/script to be launched in parallel, """
"""followed by all the arguments for the """
"""training script"""
) ,)
# rest from the training program
parser.add_argument("""training_script_args""" ,nargs=snake_case_ )
return parser.parse_args()
def __snake_case ( ) -> Union[str, Any]:
lowercase : Dict = parse_args()
# Import training_script as a module.
lowercase : List[Any] = Path(args.training_script )
sys.path.append(str(script_fpath.parent.resolve() ) )
lowercase : Optional[Any] = script_fpath.stem
lowercase : Dict = importlib.import_module(snake_case_ )
# Patch sys.argv
lowercase : List[str] = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )]
xmp.spawn(mod._mp_fn ,args=() ,nprocs=args.num_cores )
if __name__ == "__main__":
main()
| 607 | def A__ ( snake_case_ : int ):
if upper_limit < 0:
raise ValueError('''Limit for the Catalan sequence must be ≥ 0''' )
SCREAMING_SNAKE_CASE__: List[Any]= [0] * (upper_limit + 1)
# Base case: C(0) = C(1) = 1
SCREAMING_SNAKE_CASE__: List[str]= 1
if upper_limit > 0:
SCREAMING_SNAKE_CASE__: List[str]= 1
# Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
for i in range(2 , upper_limit + 1 ):
for j in range(snake_case_ ):
catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]
return catalan_list
if __name__ == "__main__":
print('\n********* Catalan Numbers Using Dynamic Programming ************\n')
print('\n*** Enter -1 at any time to quit ***')
print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='')
try:
while True:
lowercase_ : Any = int(input().strip())
if N < 0:
print('\n********* Goodbye!! ************')
break
else:
print(f'''The Catalan numbers from 0 through {N} are:''')
print(catalan_numbers(N))
print('Try another upper limit for the sequence: ', end='')
except (NameError, ValueError):
print('\n********* Invalid input, goodbye! ************\n')
import doctest
doctest.testmod()
| 64 | 0 |
"""simple docstring"""
import unittest
import numpy as np
from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.distilbert.modeling_flax_distilbert import (
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertModel,
)
class snake_case ( unittest.TestCase ):
'''simple docstring'''
def __init__( self : Tuple , __lowercase : List[str] , __lowercase : str=13 , __lowercase : Union[str, Any]=7 , __lowercase : Union[str, Any]=True , __lowercase : Union[str, Any]=True , __lowercase : Optional[int]=True , __lowercase : str=True , __lowercase : Union[str, Any]=99 , __lowercase : Union[str, Any]=32 , __lowercase : str=5 , __lowercase : str=4 , __lowercase : Optional[Any]=37 , __lowercase : Union[str, Any]="gelu" , __lowercase : List[str]=0.1 , __lowercase : Dict=0.1 , __lowercase : Dict=512 , __lowercase : Any=16 , __lowercase : Optional[Any]=2 , __lowercase : Any=0.0_2 , __lowercase : List[str]=4 , ):
'''simple docstring'''
__UpperCAmelCase : List[Any] = parent
__UpperCAmelCase : str = batch_size
__UpperCAmelCase : Optional[int] = seq_length
__UpperCAmelCase : str = is_training
__UpperCAmelCase : str = use_attention_mask
__UpperCAmelCase : int = use_token_type_ids
__UpperCAmelCase : List[Any] = use_labels
__UpperCAmelCase : str = vocab_size
__UpperCAmelCase : Dict = hidden_size
__UpperCAmelCase : Tuple = num_hidden_layers
__UpperCAmelCase : str = num_attention_heads
__UpperCAmelCase : Any = intermediate_size
__UpperCAmelCase : Optional[Any] = hidden_act
__UpperCAmelCase : List[str] = hidden_dropout_prob
__UpperCAmelCase : Tuple = attention_probs_dropout_prob
__UpperCAmelCase : Tuple = max_position_embeddings
__UpperCAmelCase : Dict = type_vocab_size
__UpperCAmelCase : List[Any] = type_sequence_label_size
__UpperCAmelCase : Dict = initializer_range
__UpperCAmelCase : List[Any] = num_choices
def A_ ( self : int ):
'''simple docstring'''
__UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__UpperCAmelCase : List[Any] = None
if self.use_attention_mask:
__UpperCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] )
__UpperCAmelCase : Optional[Any] = 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 , tie_weights_=__lowercase , )
return config, input_ids, attention_mask
def A_ ( self : Dict ):
'''simple docstring'''
__UpperCAmelCase : List[str] = self.prepare_config_and_inputs()
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Dict = config_and_inputs
__UpperCAmelCase : Tuple = {'''input_ids''': input_ids, '''attention_mask''': attention_mask}
return config, inputs_dict
@require_flax
class snake_case ( lowercase__ , unittest.TestCase ):
'''simple docstring'''
_A : List[Any] = (
(
FlaxDistilBertModel,
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def A_ ( self : Optional[int] ):
'''simple docstring'''
__UpperCAmelCase : List[Any] = FlaxDistilBertModelTester(self )
@slow
def A_ ( self : int ):
'''simple docstring'''
for model_class_name in self.all_model_classes:
__UpperCAmelCase : Any = model_class_name.from_pretrained('''distilbert-base-uncased''' )
__UpperCAmelCase : Optional[int] = model(np.ones((1, 1) ) )
self.assertIsNotNone(__lowercase )
@require_flax
class snake_case ( unittest.TestCase ):
'''simple docstring'''
@slow
def A_ ( self : List[str] ):
'''simple docstring'''
__UpperCAmelCase : Optional[int] = FlaxDistilBertModel.from_pretrained('''distilbert-base-uncased''' )
__UpperCAmelCase : Optional[Any] = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] )
__UpperCAmelCase : Any = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
__UpperCAmelCase : str = model(__lowercase , attention_mask=__lowercase )[0]
__UpperCAmelCase : str = (1, 11, 768)
self.assertEqual(output.shape , __lowercase )
__UpperCAmelCase : List[str] = np.array([[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]] )
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , __lowercase , atol=1e-4 ) ) | 701 |
"""simple docstring"""
def lowerCamelCase_ ( UpperCAmelCase_ = 10_00 ) ->int:
"""simple docstring"""
return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) )
if __name__ == "__main__":
print(solution()) | 374 | 0 |
'''simple docstring'''
from ....configuration_utils import PretrainedConfig
from ....utils import logging
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
_SCREAMING_SNAKE_CASE = {
"speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json",
# See all M-CTC-T models at https://huggingface.co/models?filter=mctct
}
class lowerCAmelCase_ ( __magic_name__ ):
__lowerCamelCase : Any = "mctct"
def __init__( self , _lowerCAmelCase=8065 , _lowerCAmelCase=1536 , _lowerCAmelCase=36 , _lowerCAmelCase=6144 , _lowerCAmelCase=4 , _lowerCAmelCase=384 , _lowerCAmelCase=920 , _lowerCAmelCase=1E-5 , _lowerCAmelCase=0.3 , _lowerCAmelCase="relu" , _lowerCAmelCase=0.02 , _lowerCAmelCase=0.3 , _lowerCAmelCase=0.3 , _lowerCAmelCase=1 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=1 , _lowerCAmelCase=0.3 , _lowerCAmelCase=1 , _lowerCAmelCase=(7,) , _lowerCAmelCase=(3,) , _lowerCAmelCase=80 , _lowerCAmelCase=1 , _lowerCAmelCase=None , _lowerCAmelCase="sum" , _lowerCAmelCase=False , **_lowerCAmelCase , ) -> int:
super().__init__(**_lowerCAmelCase , pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase )
_lowerCAmelCase = vocab_size
_lowerCAmelCase = hidden_size
_lowerCAmelCase = num_hidden_layers
_lowerCAmelCase = intermediate_size
_lowerCAmelCase = num_attention_heads
_lowerCAmelCase = attention_head_dim
_lowerCAmelCase = max_position_embeddings
_lowerCAmelCase = layer_norm_eps
_lowerCAmelCase = layerdrop
_lowerCAmelCase = hidden_act
_lowerCAmelCase = initializer_range
_lowerCAmelCase = hidden_dropout_prob
_lowerCAmelCase = attention_probs_dropout_prob
_lowerCAmelCase = pad_token_id
_lowerCAmelCase = bos_token_id
_lowerCAmelCase = eos_token_id
_lowerCAmelCase = conv_glu_dim
_lowerCAmelCase = conv_dropout
_lowerCAmelCase = num_conv_layers
_lowerCAmelCase = input_feat_per_channel
_lowerCAmelCase = input_channels
_lowerCAmelCase = conv_channels
_lowerCAmelCase = ctc_loss_reduction
_lowerCAmelCase = ctc_zero_infinity
# prevents config testing fail with exporting to json
_lowerCAmelCase = list(_lowerCAmelCase )
_lowerCAmelCase = list(_lowerCAmelCase )
if len(self.conv_kernel ) != self.num_conv_layers:
raise ValueError(
"Configuration for convolutional module is incorrect. "
"It is required that `len(config.conv_kernel)` == `config.num_conv_layers` "
f'''but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, '''
f'''`config.num_conv_layers = {self.num_conv_layers}`.''' )
| 18 |
import argparse
import json
import os
import re
import shutil
import torch
from transformers import BioGptConfig, BioGptForCausalLM
from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging
logging.set_verbosity_warning()
a = 2
class UpperCamelCase__ :
def __init__( self : Any , *, # begin keyword-only arguments
UpperCamelCase__ : Any="<s>" , UpperCamelCase__ : int="<pad>" , UpperCamelCase__ : str="</s>" , UpperCamelCase__ : int="<unk>" , UpperCamelCase__ : Dict=None , ):
'''simple docstring'''
lowercase_ , lowercase_ , lowercase_ , lowercase_ = bos, unk, pad, eos
lowercase_ = []
lowercase_ = []
lowercase_ = {}
lowercase_ = self.add_symbol(UpperCamelCase__ )
lowercase_ = self.add_symbol(UpperCamelCase__ )
lowercase_ = self.add_symbol(UpperCamelCase__ )
lowercase_ = self.add_symbol(UpperCamelCase__ )
if extra_special_symbols:
for s in extra_special_symbols:
self.add_symbol(UpperCamelCase__ )
lowercase_ = len(self.symbols )
def __eq__( self : int , UpperCamelCase__ : Union[str, Any] ):
'''simple docstring'''
return self.indices == other.indices
def __getitem__( self : Optional[Any] , UpperCamelCase__ : str ):
'''simple docstring'''
if idx < len(self.symbols ):
return self.symbols[idx]
return self.unk_word
def __len__( self : List[Any] ):
'''simple docstring'''
return len(self.symbols )
def __contains__( self : Any , UpperCamelCase__ : Optional[Any] ):
'''simple docstring'''
return sym in self.indices
@classmethod
def UpperCAmelCase__ ( cls : Optional[Any] , UpperCamelCase__ : Dict ):
'''simple docstring'''
lowercase_ = cls()
d.add_from_file(UpperCamelCase__ )
return d
def UpperCAmelCase__ ( self : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[int]=1 , UpperCamelCase__ : Any=False ):
'''simple docstring'''
if word in self.indices and not overwrite:
lowercase_ = self.indices[word]
lowercase_ = self.count[idx] + n
return idx
else:
lowercase_ = len(self.symbols )
lowercase_ = idx
self.symbols.append(UpperCamelCase__ )
self.count.append(UpperCamelCase__ )
return idx
def UpperCAmelCase__ ( self : Dict , UpperCamelCase__ : Union[str, Any] ):
'''simple docstring'''
return 0
def UpperCAmelCase__ ( self : List[Any] , UpperCamelCase__ : Dict ):
'''simple docstring'''
if isinstance(UpperCamelCase__ , UpperCamelCase__ ):
try:
with open(UpperCamelCase__ , """r""" , encoding="""utf-8""" ) as fd:
self.add_from_file(UpperCamelCase__ )
except FileNotFoundError as fnfe:
raise fnfe
except UnicodeError:
raise Exception("""Incorrect encoding detected in {}, please rebuild the dataset""".format(UpperCamelCase__ ) )
return
lowercase_ = f.readlines()
lowercase_ = self._load_meta(UpperCamelCase__ )
for line in lines[indices_start_line:]:
try:
lowercase_ , lowercase_ = line.rstrip().rsplit(""" """ , 1 )
if field == "#fairseq:overwrite":
lowercase_ = True
lowercase_ , lowercase_ = line.rsplit(""" """ , 1 )
else:
lowercase_ = False
lowercase_ = int(UpperCamelCase__ )
lowercase_ = line
if word in self and not overwrite:
raise RuntimeError(
"""Duplicate word found when loading Dictionary: '{}'. """
"""Duplicate words can overwrite earlier ones by adding the """
"""#fairseq:overwrite flag at the end of the corresponding row """
"""in the dictionary file. If using the Camembert model, please """
"""download an updated copy of the model file.""".format(UpperCamelCase__ ) )
self.add_symbol(UpperCamelCase__ , n=UpperCamelCase__ , overwrite=UpperCamelCase__ )
except ValueError:
raise ValueError("""Incorrect dictionary format, expected '<token> <cnt> [flags]'""" )
def UpperCAmelCase_ ( UpperCAmelCase__ ):
# (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up,
# e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7}
lowercase_ = dict((re.sub(r"""@@$""" , """""" , UpperCAmelCase__ ), v) if k.endswith("""@@""" ) else (re.sub(r"""$""" , """</w>""" , UpperCAmelCase__ ), v) for k, v in d.items() )
lowercase_ = """<s> <pad> </s> <unk>""".split()
# restore the special tokens
for k in keep_keys:
del da[F'''{k}</w>''']
lowercase_ = d[k] # restore
return da
def UpperCAmelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
# prep
if not os.path.exists(UpperCAmelCase__ ):
raise ValueError(F'''path {biogpt_checkpoint_path} does not exist!''' )
os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ )
print(F'''Writing results to {pytorch_dump_folder_path}''' )
# handle various types of models
lowercase_ = os.path.join(UpperCAmelCase__ , """checkpoint.pt""" )
if not os.path.isfile(UpperCAmelCase__ ):
raise ValueError(F'''path to the file {checkpoint_file} does not exist!''' )
lowercase_ = torch.load(UpperCAmelCase__ , map_location="""cpu""" )
lowercase_ = chkpt["""cfg"""]["""model"""]
# dicts
lowercase_ = os.path.join(UpperCAmelCase__ , """dict.txt""" )
if not os.path.isfile(UpperCAmelCase__ ):
raise ValueError(F'''path to the file {dict_file} does not exist!''' )
lowercase_ = Dictionary.load(UpperCAmelCase__ )
lowercase_ = rewrite_dict_keys(src_dict.indices )
lowercase_ = len(UpperCAmelCase__ )
lowercase_ = os.path.join(UpperCAmelCase__ , VOCAB_FILES_NAMES["""vocab_file"""] )
print(F'''Generating {src_vocab_file} of {src_vocab_size} records''' )
with open(UpperCAmelCase__ , """w""" , encoding="""utf-8""" ) as f:
f.write(json.dumps(UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ , indent=UpperCAmelCase__ ) )
# merges_file (bpecodes)
lowercase_ = os.path.join(UpperCAmelCase__ , """bpecodes""" )
if not os.path.isfile(UpperCAmelCase__ ):
raise ValueError(F'''path to the file {bpecodes_file} does not exist!''' )
lowercase_ = os.path.join(UpperCAmelCase__ , VOCAB_FILES_NAMES["""merges_file"""] )
shutil.copyfile(UpperCAmelCase__ , UpperCAmelCase__ )
# model config
lowercase_ = os.path.join(UpperCAmelCase__ , """config.json""" )
lowercase_ = {
"""activation_dropout""": args["""activation_dropout"""],
"""architectures""": ["""BioGptForCausalLM"""],
"""attention_probs_dropout_prob""": args["""attention_dropout"""],
"""bos_token_id""": 0,
"""eos_token_id""": 2,
"""hidden_act""": args["""activation_fn"""],
"""hidden_dropout_prob""": args["""dropout"""],
"""hidden_size""": args["""decoder_embed_dim"""],
"""initializer_range""": 0.02,
"""intermediate_size""": args["""decoder_ffn_embed_dim"""],
"""layer_norm_eps""": 1e-12,
"""layerdrop""": args["""decoder_layerdrop"""],
"""max_position_embeddings""": args["""max_target_positions"""],
"""model_type""": """biogpt""",
"""num_attention_heads""": args["""decoder_attention_heads"""],
"""num_hidden_layers""": args["""decoder_layers"""],
"""pad_token_id""": 1,
"""scale_embedding""": not args["""no_scale_embedding"""],
"""tie_word_embeddings""": args["""share_decoder_input_output_embed"""],
"""vocab_size""": src_vocab_size,
}
# good hparam defaults to start with
print(F'''Generating {biogpt_model_config_file}''' )
with open(UpperCAmelCase__ , """w""" , encoding="""utf-8""" ) as f:
f.write(json.dumps(UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ , indent=UpperCAmelCase__ ) )
# tokenizer config
lowercase_ = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ )
lowercase_ = {
"""bos_token""": """<s>""",
"""eos_token""": """</s>""",
"""model_max_length""": 1_0_2_4,
"""pad_token""": """<pad>""",
"""special_tokens_map_file""": None,
"""tokenizer_class""": """BioGptTokenizer""",
"""unk_token""": """<unk>""",
}
print(F'''Generating {biogpt_tokenizer_config_file}''' )
with open(UpperCAmelCase__ , """w""" , encoding="""utf-8""" ) as f:
f.write(json.dumps(UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ , indent=UpperCAmelCase__ ) )
# model
lowercase_ = chkpt["""model"""]
# remove unneeded keys
lowercase_ = [
"""decoder.version""",
]
for k in ignore_keys:
model_state_dict.pop(UpperCAmelCase__ , UpperCAmelCase__ )
lowercase_ = list(model_state_dict.keys() )
for layer_name in layer_names:
if layer_name.endswith("""output_projection.weight""" ):
lowercase_ = model_state_dict.pop(UpperCAmelCase__ )
else:
lowercase_ = model_state_dict.pop(UpperCAmelCase__ )
lowercase_ = BioGptConfig.from_pretrained(UpperCAmelCase__ )
lowercase_ = BioGptForCausalLM(UpperCAmelCase__ )
# check that it loads ok
model_new.load_state_dict(UpperCAmelCase__ )
# save
lowercase_ = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ )
print(F'''Generating {pytorch_weights_dump_path}''' )
torch.save(UpperCAmelCase__ , UpperCAmelCase__ )
print("""Conversion is done!""" )
if __name__ == "__main__":
a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--biogpt_checkpoint_path',
default=None,
type=str,
required=True,
help=(
'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,'
' bpecodes, etc.'
),
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
a = parser.parse_args()
convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
| 412 | 0 |
"""simple docstring"""
def _snake_case ( lowercase__ ):
_lowerCamelCase : Optional[int] = int(lowercase__ )
if decimal in (0, 1): # Exit cases for the recursion
return str(lowercase__ )
_lowerCamelCase, _lowerCamelCase : Dict = divmod(lowercase__ , 2 )
return binary_recursive(lowercase__ ) + str(lowercase__ )
def _snake_case ( lowercase__ ):
_lowerCamelCase : List[Any] = str(lowercase__ ).strip()
if not number:
raise ValueError('No input value was provided' )
_lowerCamelCase : str = '-' if number.startswith('-' ) else ''
_lowerCamelCase : Union[str, Any] = number.lstrip('-' )
if not number.isnumeric():
raise ValueError('Input value is not an integer' )
return f'''{negative}0b{binary_recursive(int(lowercase__ ) )}'''
if __name__ == "__main__":
from doctest import testmod
testmod() | 492 |
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DetrImageProcessor
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , lowercase , lowercase=7 , lowercase=3 , lowercase=30 , lowercase=400 , lowercase=True , lowercase=None , lowercase=True , lowercase=1 / 255 , lowercase=True , lowercase=[0.5, 0.5, 0.5] , lowercase=[0.5, 0.5, 0.5] , lowercase=True , ):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
_lowerCamelCase : Any = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333}
_lowerCamelCase : Optional[int] = parent
_lowerCamelCase : Any = batch_size
_lowerCamelCase : int = num_channels
_lowerCamelCase : Union[str, Any] = min_resolution
_lowerCamelCase : List[Any] = max_resolution
_lowerCamelCase : Union[str, Any] = do_resize
_lowerCamelCase : str = size
_lowerCamelCase : List[str] = do_rescale
_lowerCamelCase : Optional[int] = rescale_factor
_lowerCamelCase : str = do_normalize
_lowerCamelCase : Optional[int] = image_mean
_lowerCamelCase : Tuple = image_std
_lowerCamelCase : Tuple = do_pad
def A_ ( self ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_pad": self.do_pad,
}
def A_ ( self , lowercase , lowercase=False ):
if not batched:
_lowerCamelCase : Union[str, Any] = image_inputs[0]
if isinstance(lowercase , Image.Image ):
_lowerCamelCase, _lowerCamelCase : Optional[Any] = image.size
else:
_lowerCamelCase, _lowerCamelCase : List[str] = image.shape[1], image.shape[2]
if w < h:
_lowerCamelCase : List[Any] = int(self.size['shortest_edge'] * h / w )
_lowerCamelCase : Union[str, Any] = self.size['shortest_edge']
elif w > h:
_lowerCamelCase : List[str] = self.size['shortest_edge']
_lowerCamelCase : Optional[Any] = int(self.size['shortest_edge'] * w / h )
else:
_lowerCamelCase : int = self.size['shortest_edge']
_lowerCamelCase : Optional[Any] = self.size['shortest_edge']
else:
_lowerCamelCase : Union[str, Any] = []
for image in image_inputs:
_lowerCamelCase, _lowerCamelCase : Tuple = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
_lowerCamelCase : Tuple = max(lowercase , key=lambda lowercase : item[0] )[0]
_lowerCamelCase : Any = max(lowercase , key=lambda lowercase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class lowerCAmelCase__ ( lowercase, unittest.TestCase ):
'''simple docstring'''
lowerCamelCase__ = DetrImageProcessor if is_vision_available() else None
def A_ ( self ):
_lowerCamelCase : int = DetrImageProcessingTester(self )
@property
def A_ ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def A_ ( self ):
_lowerCamelCase : str = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(lowercase , 'image_mean' ) )
self.assertTrue(hasattr(lowercase , 'image_std' ) )
self.assertTrue(hasattr(lowercase , 'do_normalize' ) )
self.assertTrue(hasattr(lowercase , 'do_rescale' ) )
self.assertTrue(hasattr(lowercase , 'rescale_factor' ) )
self.assertTrue(hasattr(lowercase , 'do_resize' ) )
self.assertTrue(hasattr(lowercase , 'size' ) )
self.assertTrue(hasattr(lowercase , 'do_pad' ) )
def A_ ( self ):
_lowerCamelCase : List[str] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} )
self.assertEqual(image_processor.do_pad , lowercase )
_lowerCamelCase : Union[str, Any] = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowercase )
self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} )
self.assertEqual(image_processor.do_pad , lowercase )
def A_ ( self ):
pass
def A_ ( self ):
# Initialize image_processing
_lowerCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_lowerCamelCase : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase )
for image in image_inputs:
self.assertIsInstance(lowercase , Image.Image )
# Test not batched input
_lowerCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
_lowerCamelCase, _lowerCamelCase : List[Any] = self.image_processor_tester.get_expected_values(lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
_lowerCamelCase, _lowerCamelCase : str = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase )
_lowerCamelCase : Union[str, Any] = image_processing(lowercase , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def A_ ( self ):
# Initialize image_processing
_lowerCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_lowerCamelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , numpify=lowercase )
for image in image_inputs:
self.assertIsInstance(lowercase , np.ndarray )
# Test not batched input
_lowerCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
_lowerCamelCase, _lowerCamelCase : List[Any] = self.image_processor_tester.get_expected_values(lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
_lowerCamelCase : str = image_processing(lowercase , return_tensors='pt' ).pixel_values
_lowerCamelCase, _lowerCamelCase : Union[str, Any] = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def A_ ( self ):
# Initialize image_processing
_lowerCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_lowerCamelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , torchify=lowercase )
for image in image_inputs:
self.assertIsInstance(lowercase , torch.Tensor )
# Test not batched input
_lowerCamelCase : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
_lowerCamelCase, _lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(lowercase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
_lowerCamelCase : Dict = image_processing(lowercase , return_tensors='pt' ).pixel_values
_lowerCamelCase, _lowerCamelCase : List[str] = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def A_ ( self ):
# prepare image and target
_lowerCamelCase : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f:
_lowerCamelCase : int = json.loads(f.read() )
_lowerCamelCase : str = {'image_id': 39769, 'annotations': target}
# encode them
_lowerCamelCase : str = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' )
_lowerCamelCase : int = image_processing(images=lowercase , annotations=lowercase , return_tensors='pt' )
# verify pixel values
_lowerCamelCase : Optional[Any] = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding['pixel_values'].shape , lowercase )
_lowerCamelCase : List[str] = torch.tensor([0.27_96, 0.31_38, 0.34_81] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , lowercase , atol=1E-4 ) )
# verify area
_lowerCamelCase : Dict = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , lowercase ) )
# verify boxes
_lowerCamelCase : int = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , lowercase )
_lowerCamelCase : Tuple = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , lowercase , atol=1E-3 ) )
# verify image_id
_lowerCamelCase : List[Any] = torch.tensor([39769] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , lowercase ) )
# verify is_crowd
_lowerCamelCase : str = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , lowercase ) )
# verify class_labels
_lowerCamelCase : Dict = torch.tensor([75, 75, 63, 65, 17, 17] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , lowercase ) )
# verify orig_size
_lowerCamelCase : Optional[int] = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , lowercase ) )
# verify size
_lowerCamelCase : List[str] = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , lowercase ) )
@slow
def A_ ( self ):
# prepare image, target and masks_path
_lowerCamelCase : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f:
_lowerCamelCase : List[Any] = json.loads(f.read() )
_lowerCamelCase : str = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target}
_lowerCamelCase : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' )
# encode them
_lowerCamelCase : List[Any] = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' )
_lowerCamelCase : Dict = image_processing(images=lowercase , annotations=lowercase , masks_path=lowercase , return_tensors='pt' )
# verify pixel values
_lowerCamelCase : Optional[int] = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding['pixel_values'].shape , lowercase )
_lowerCamelCase : List[Any] = torch.tensor([0.27_96, 0.31_38, 0.34_81] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , lowercase , atol=1E-4 ) )
# verify area
_lowerCamelCase : Optional[Any] = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , lowercase ) )
# verify boxes
_lowerCamelCase : Dict = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , lowercase )
_lowerCamelCase : Union[str, Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , lowercase , atol=1E-3 ) )
# verify image_id
_lowerCamelCase : List[str] = torch.tensor([39769] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , lowercase ) )
# verify is_crowd
_lowerCamelCase : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , lowercase ) )
# verify class_labels
_lowerCamelCase : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , lowercase ) )
# verify masks
_lowerCamelCase : List[str] = 822873
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , lowercase )
# verify orig_size
_lowerCamelCase : Optional[Any] = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , lowercase ) )
# verify size
_lowerCamelCase : List[str] = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , lowercase ) ) | 492 | 1 |
"""simple docstring"""
from __future__ import annotations
import math
def UpperCamelCase ( _A ) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(_A ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def UpperCamelCase ( _A ) -> list[int]:
lowercase : Tuple = str(_A )
lowercase : int = [n]
for i in range(1 , len(_A ) ):
list_nums.append(int(str_num[i:] ) )
list_nums.append(int(str_num[:-i] ) )
return list_nums
def UpperCamelCase ( _A ) -> bool:
if len(str(_A ) ) > 3:
if not is_prime(int(str(_A )[-3:] ) ) or not is_prime(int(str(_A )[:3] ) ):
return False
return True
def UpperCamelCase ( _A = 11 ) -> list[int]:
lowercase : list[int] = []
lowercase : int = 13
while len(_A ) != count:
if validate(_A ):
lowercase : List[str] = list_truncated_nums(_A )
if all(is_prime(_A ) for i in list_nums ):
list_truncated_primes.append(_A )
num += 2
return list_truncated_primes
def UpperCamelCase ( ) -> int:
return sum(compute_truncated_primes(11 ) )
if __name__ == "__main__":
print(F'{sum(compute_truncated_primes(11)) = }')
| 264 |
"""simple docstring"""
def UpperCamelCase ( _A , _A ) -> int:
lowercase : int = 1 # To kept the Calculated Value
# Since C(n, k) = C(n, n-k)
if k > (n - k):
lowercase : List[Any] = n - k
# Calculate C(n,k)
for i in range(_A ):
result *= n - i
result //= i + 1
return result
def UpperCamelCase ( _A ) -> int:
return binomial_coefficient(2 * node_count , _A ) // (node_count + 1)
def UpperCamelCase ( _A ) -> int:
if n < 0:
raise ValueError("""factorial() not defined for negative values""" )
lowercase : Union[str, Any] = 1
for i in range(1 , n + 1 ):
result *= i
return result
def UpperCamelCase ( _A ) -> int:
return catalan_number(_A ) * factorial(_A )
if __name__ == "__main__":
_lowerCAmelCase = int(input('Enter the number of nodes: ').strip() or 0)
if node_count <= 0:
raise ValueError('We need some nodes to work with.')
print(
F'Given {node_count} nodes, there are {binary_tree_count(node_count)} '
F'binary trees and {catalan_number(node_count)} binary search trees.'
)
| 264 | 1 |
"""simple docstring"""
import copy
from typing import Dict, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
from ..detr import DetrConfig
from ..swin import SwinConfig
A__ : List[Any] = {
"facebook/maskformer-swin-base-ade": (
"https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json"
)
# See all MaskFormer models at https://huggingface.co/models?filter=maskformer
}
A__ : str = logging.get_logger(__name__)
class _lowercase ( _UpperCAmelCase ):
'''simple docstring'''
_A = '''maskformer'''
_A = {'''hidden_size''': '''mask_feature_size'''}
_A = ['''resnet''', '''swin''']
_A = ['''detr''']
def __init__( self , __UpperCamelCase = 2_56 , __UpperCamelCase = 2_56 , __UpperCamelCase = 0.1 , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = 0.02 , __UpperCamelCase = 1.0 , __UpperCamelCase = 1.0 , __UpperCamelCase = 1.0 , __UpperCamelCase = 20.0 , __UpperCamelCase = None , **__UpperCamelCase , )-> List[str]:
if backbone_config is None:
# fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k
UpperCAmelCase__ : int = SwinConfig(
image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=["stage1", "stage2", "stage3", "stage4"] , )
if isinstance(A_ , A_ ):
UpperCAmelCase__ : Optional[int] = backbone_config.pop("model_type" )
UpperCAmelCase__ : Tuple = CONFIG_MAPPING[backbone_model_type]
UpperCAmelCase__ : List[str] = config_class.from_dict(A_ )
# verify that the backbone is supported
if backbone_config.model_type not in self.backbones_supported:
logger.warning_once(
F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. "
F"Supported model types: {','.join(self.backbones_supported )}" )
if decoder_config is None:
# fall back to https://huggingface.co/facebook/detr-resnet-50
UpperCAmelCase__ : Tuple = DetrConfig()
else:
# verify that the decoder is supported
UpperCAmelCase__ : int = (
decoder_config.pop("model_type" ) if isinstance(A_ , A_ ) else decoder_config.model_type
)
if decoder_type not in self.decoders_supported:
raise ValueError(
F"Transformer Decoder {decoder_type} not supported, please use one of"
F" {','.join(self.decoders_supported )}" )
if isinstance(A_ , A_ ):
UpperCAmelCase__ : List[Any] = CONFIG_MAPPING[decoder_type]
UpperCAmelCase__ : Union[str, Any] = config_class.from_dict(A_ )
UpperCAmelCase__ : Union[str, Any] = backbone_config
UpperCAmelCase__ : Union[str, Any] = decoder_config
# main feature dimension for the model
UpperCAmelCase__ : Optional[Any] = fpn_feature_size
UpperCAmelCase__ : Union[str, Any] = mask_feature_size
# initializer
UpperCAmelCase__ : List[Any] = init_std
UpperCAmelCase__ : List[str] = init_xavier_std
# Hungarian matcher && loss
UpperCAmelCase__ : Dict = cross_entropy_weight
UpperCAmelCase__ : Union[str, Any] = dice_weight
UpperCAmelCase__ : Union[str, Any] = mask_weight
UpperCAmelCase__ : str = use_auxiliary_loss
UpperCAmelCase__ : int = no_object_weight
UpperCAmelCase__ : Dict = output_auxiliary_logits
UpperCAmelCase__ : Optional[Any] = self.decoder_config.encoder_attention_heads
UpperCAmelCase__ : List[Any] = self.decoder_config.num_hidden_layers
super().__init__(**A_ )
@classmethod
def lowerCAmelCase__ ( cls , __UpperCamelCase , __UpperCamelCase , **__UpperCamelCase )-> Union[str, Any]:
return cls(
backbone_config=A_ , decoder_config=A_ , **A_ , )
def lowerCAmelCase__ ( self )-> Dict[str, any]:
UpperCAmelCase__ : Dict = copy.deepcopy(self.__dict__ )
UpperCAmelCase__ : Optional[int] = self.backbone_config.to_dict()
UpperCAmelCase__ : Dict = self.decoder_config.to_dict()
UpperCAmelCase__ : Tuple = self.__class__.model_type
return output
| 705 |
"""simple docstring"""
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import flax
import jax
import jax.numpy as jnp
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
CommonSchedulerState,
FlaxKarrasDiffusionSchedulers,
FlaxSchedulerMixin,
FlaxSchedulerOutput,
add_noise_common,
get_velocity_common,
)
@flax.struct.dataclass
class _lowercase :
'''simple docstring'''
_A = 42
# setable values
_A = 42
_A = 42
_A = None
@classmethod
def lowerCAmelCase__ ( cls , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> Union[str, Any]:
return cls(common=__UpperCamelCase , init_noise_sigma=__UpperCamelCase , timesteps=__UpperCamelCase )
@dataclass
class _lowercase ( lowerCAmelCase_ ):
'''simple docstring'''
_A = 42
class _lowercase ( lowerCAmelCase_ , lowerCAmelCase_ ):
'''simple docstring'''
_A = [e.name for e in FlaxKarrasDiffusionSchedulers]
_A = 42
@property
def lowerCAmelCase__ ( self )-> Optional[int]:
return True
@register_to_config
def __init__( self , __UpperCamelCase = 10_00 , __UpperCamelCase = 0.0001 , __UpperCamelCase = 0.02 , __UpperCamelCase = "linear" , __UpperCamelCase = None , __UpperCamelCase = "fixed_small" , __UpperCamelCase = True , __UpperCamelCase = "epsilon" , __UpperCamelCase = jnp.floataa , )-> List[str]:
UpperCAmelCase__ : int = dtype
def lowerCAmelCase__ ( self , __UpperCamelCase = None )-> DDPMSchedulerState:
if common is None:
UpperCAmelCase__ : int = CommonSchedulerState.create(self )
# standard deviation of the initial noise distribution
UpperCAmelCase__ : Tuple = jnp.array(1.0 , dtype=self.dtype )
UpperCAmelCase__ : Tuple = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1]
return DDPMSchedulerState.create(
common=__UpperCamelCase , init_noise_sigma=__UpperCamelCase , timesteps=__UpperCamelCase , )
def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None )-> jnp.ndarray:
return sample
def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = () )-> DDPMSchedulerState:
UpperCAmelCase__ : Dict = self.config.num_train_timesteps // num_inference_steps
# creates integer timesteps by multiplying by ratio
# rounding to avoid issues when num_inference_step is power of 3
UpperCAmelCase__ : Optional[int] = (jnp.arange(0 , __UpperCamelCase ) * step_ratio).round()[::-1]
return state.replace(
num_inference_steps=__UpperCamelCase , timesteps=__UpperCamelCase , )
def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None , __UpperCamelCase=None )-> Union[str, Any]:
UpperCAmelCase__ : Optional[Any] = state.common.alphas_cumprod[t]
UpperCAmelCase__ : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
# For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
# and sample from it to get previous sample
# x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
UpperCAmelCase__ : Any = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t]
if variance_type is None:
UpperCAmelCase__ : Union[str, Any] = self.config.variance_type
# hacks - were probably added for training stability
if variance_type == "fixed_small":
UpperCAmelCase__ : Dict = jnp.clip(__UpperCamelCase , a_min=1E-20 )
# for rl-diffuser https://arxiv.org/abs/2205.09991
elif variance_type == "fixed_small_log":
UpperCAmelCase__ : Tuple = jnp.log(jnp.clip(__UpperCamelCase , a_min=1E-20 ) )
elif variance_type == "fixed_large":
UpperCAmelCase__ : Union[str, Any] = state.common.betas[t]
elif variance_type == "fixed_large_log":
# Glide max_log
UpperCAmelCase__ : Optional[int] = jnp.log(state.common.betas[t] )
elif variance_type == "learned":
return predicted_variance
elif variance_type == "learned_range":
UpperCAmelCase__ : List[str] = variance
UpperCAmelCase__ : Union[str, Any] = state.common.betas[t]
UpperCAmelCase__ : Optional[int] = (predicted_variance + 1) / 2
UpperCAmelCase__ : Any = frac * max_log + (1 - frac) * min_log
return variance
def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = True , )-> Union[FlaxDDPMSchedulerOutput, Tuple]:
UpperCAmelCase__ : List[str] = timestep
if key is None:
UpperCAmelCase__ : int = jax.random.PRNGKey(0 )
if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]:
UpperCAmelCase__ , UpperCAmelCase__ : List[str] = jnp.split(__UpperCamelCase , sample.shape[1] , axis=1 )
else:
UpperCAmelCase__ : Optional[Any] = None
# 1. compute alphas, betas
UpperCAmelCase__ : Union[str, Any] = state.common.alphas_cumprod[t]
UpperCAmelCase__ : Tuple = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
UpperCAmelCase__ : Union[str, Any] = 1 - alpha_prod_t
UpperCAmelCase__ : Tuple = 1 - alpha_prod_t_prev
# 2. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
if self.config.prediction_type == "epsilon":
UpperCAmelCase__ : List[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif self.config.prediction_type == "sample":
UpperCAmelCase__ : Any = model_output
elif self.config.prediction_type == "v_prediction":
UpperCAmelCase__ : Union[str, Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
else:
raise ValueError(
F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` "
" for the FlaxDDPMScheduler." )
# 3. Clip "predicted x_0"
if self.config.clip_sample:
UpperCAmelCase__ : List[Any] = jnp.clip(__UpperCamelCase , -1 , 1 )
# 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
UpperCAmelCase__ : List[str] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t
UpperCAmelCase__ : List[Any] = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t
# 5. Compute predicted previous sample µ_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
UpperCAmelCase__ : Tuple = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
def random_variance():
UpperCAmelCase__ : Any = jax.random.split(__UpperCamelCase , num=1 )
UpperCAmelCase__ : int = jax.random.normal(__UpperCamelCase , shape=model_output.shape , dtype=self.dtype )
return (self._get_variance(__UpperCamelCase , __UpperCamelCase , predicted_variance=__UpperCamelCase ) ** 0.5) * noise
UpperCAmelCase__ : Dict = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) )
UpperCAmelCase__ : Any = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample, state)
return FlaxDDPMSchedulerOutput(prev_sample=__UpperCamelCase , state=__UpperCamelCase )
def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , )-> jnp.ndarray:
return add_noise_common(state.common , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , )-> jnp.ndarray:
return get_velocity_common(state.common , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
def __len__( self )-> Tuple:
return self.config.num_train_timesteps
| 660 | 0 |
"""simple docstring"""
import json
import os
import re
import unittest
from transformers import CodeGenTokenizer, CodeGenTokenizerFast
from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class A_(_lowerCAmelCase , unittest.TestCase ):
"""simple docstring"""
a_ : Optional[int] = CodeGenTokenizer
a_ : str = CodeGenTokenizerFast
a_ : str = True
a_ : str = {"""add_prefix_space""": True}
a_ : Union[str, Any] = False
def _lowerCAmelCase ( self ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_lowerCamelCase : Any = [
"""l""",
"""o""",
"""w""",
"""e""",
"""r""",
"""s""",
"""t""",
"""i""",
"""d""",
"""n""",
"""\u0120""",
"""\u0120l""",
"""\u0120n""",
"""\u0120lo""",
"""\u0120low""",
"""er""",
"""\u0120lowest""",
"""\u0120newer""",
"""\u0120wider""",
"""<unk>""",
"""<|endoftext|>""",
]
_lowerCamelCase : str = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) )
_lowerCamelCase : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
_lowerCamelCase : Dict = {"""unk_token""": """<unk>"""}
_lowerCamelCase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
_lowerCamelCase : 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(SCREAMING_SNAKE_CASE_ ) + '\n' )
with open(self.merges_file , 'w' , encoding='utf-8' ) as fp:
fp.write('\n'.join(SCREAMING_SNAKE_CASE_ ) )
def _lowerCAmelCase ( self , **A ):
kwargs.update(self.special_tokens_map )
return CodeGenTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ )
def _lowerCAmelCase ( self , **A ):
kwargs.update(self.special_tokens_map )
return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ )
def _lowerCAmelCase ( self , A ):
_lowerCamelCase : Dict = """lower newer"""
_lowerCamelCase : int = """lower newer"""
return input_text, output_text
def _lowerCAmelCase ( self ):
_lowerCamelCase : Optional[Any] = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_lowerCamelCase : int = """lower newer"""
_lowerCamelCase : int = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""]
_lowerCamelCase : Union[str, Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : List[str] = tokens + [tokenizer.unk_token]
_lowerCamelCase : str = [14, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
def _lowerCAmelCase ( self ):
if not self.test_rust_tokenizer:
return
_lowerCamelCase : Dict = self.get_tokenizer()
_lowerCamelCase : Union[str, Any] = self.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : Optional[Any] = """lower newer"""
# Testing tokenization
_lowerCamelCase : List[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : List[str] = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Testing conversion to ids without special tokens
_lowerCamelCase : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : int = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Testing conversion to ids with special tokens
_lowerCamelCase : Union[str, Any] = self.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : str = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ )
self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Testing the unknown token
_lowerCamelCase : Dict = tokens + [rust_tokenizer.unk_token]
_lowerCamelCase : List[str] = [14, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ )
def _lowerCAmelCase ( self , *A , **A ):
# It's very difficult to mix/test pretokenization with byte-level
# And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string)
pass
def _lowerCAmelCase ( self , A=15 ):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ):
_lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
# Simple input
_lowerCamelCase : List[Any] = """This is a simple input"""
_lowerCamelCase : Tuple = ["""This is a simple input 1""", """This is a simple input 2"""]
_lowerCamelCase : Any = ("""This is a simple input""", """This is a pair""")
_lowerCamelCase : str = [
("""This is a simple input 1""", """This is a simple input 2"""),
("""This is a simple pair 1""", """This is a simple pair 2"""),
]
# Simple input tests
self.assertRaises(SCREAMING_SNAKE_CASE_ , tokenizer_r.encode , SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding='max_length' )
# Simple input
self.assertRaises(SCREAMING_SNAKE_CASE_ , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding='max_length' )
# Simple input
self.assertRaises(
SCREAMING_SNAKE_CASE_ , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding='max_length' , )
# Pair input
self.assertRaises(SCREAMING_SNAKE_CASE_ , tokenizer_r.encode , SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding='max_length' )
# Pair input
self.assertRaises(SCREAMING_SNAKE_CASE_ , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding='max_length' )
# Pair input
self.assertRaises(
SCREAMING_SNAKE_CASE_ , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , padding='max_length' , )
def _lowerCAmelCase ( self ):
_lowerCamelCase : int = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' )
# Simple input
_lowerCamelCase : Any = """This is a simple input"""
_lowerCamelCase : Tuple = ["""This is a simple input looooooooong""", """This is a simple input"""]
_lowerCamelCase : str = ("""This is a simple input""", """This is a pair""")
_lowerCamelCase : Optional[int] = [
("""This is a simple input loooooong""", """This is a simple input"""),
("""This is a simple pair loooooong""", """This is a simple pair"""),
]
_lowerCamelCase : Dict = tokenizer.pad_token_id
_lowerCamelCase : Any = tokenizer(SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=30 , return_tensors='np' )
_lowerCamelCase : List[str] = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncate=SCREAMING_SNAKE_CASE_ , return_tensors='np' )
_lowerCamelCase : Optional[Any] = tokenizer(*SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=60 , return_tensors='np' )
_lowerCamelCase : List[str] = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncate=SCREAMING_SNAKE_CASE_ , return_tensors='np' )
# s
# test single string max_length padding
self.assertEqual(out_s['input_ids'].shape[-1] , 30 )
self.assertTrue(pad_token_id in out_s['input_ids'] )
self.assertTrue(0 in out_s['attention_mask'] )
# s2
# test automatic padding
self.assertEqual(out_sa['input_ids'].shape[-1] , 33 )
# long slice doesn't have padding
self.assertFalse(pad_token_id in out_sa['input_ids'][0] )
self.assertFalse(0 in out_sa['attention_mask'][0] )
# short slice does have padding
self.assertTrue(pad_token_id in out_sa['input_ids'][1] )
self.assertTrue(0 in out_sa['attention_mask'][1] )
# p
# test single pair max_length padding
self.assertEqual(out_p['input_ids'].shape[-1] , 60 )
self.assertTrue(pad_token_id in out_p['input_ids'] )
self.assertTrue(0 in out_p['attention_mask'] )
# p2
# test automatic padding pair
self.assertEqual(out_pa['input_ids'].shape[-1] , 52 )
# long slice pair doesn't have padding
self.assertFalse(pad_token_id in out_pa['input_ids'][0] )
self.assertFalse(0 in out_pa['attention_mask'][0] )
# short slice pair does have padding
self.assertTrue(pad_token_id in out_pa['input_ids'][1] )
self.assertTrue(0 in out_pa['attention_mask'][1] )
def _lowerCAmelCase ( self ):
_lowerCamelCase : str = """$$$"""
_lowerCamelCase : str = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=SCREAMING_SNAKE_CASE_ , add_bos_token=SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : Optional[Any] = """This is a simple input"""
_lowerCamelCase : Optional[Any] = ["""This is a simple input 1""", """This is a simple input 2"""]
_lowerCamelCase : Union[str, Any] = tokenizer.bos_token_id
_lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : List[str] = tokenizer(SCREAMING_SNAKE_CASE_ )
self.assertEqual(out_s.input_ids[0] , SCREAMING_SNAKE_CASE_ )
self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) )
_lowerCamelCase : Union[str, Any] = tokenizer.decode(out_s.input_ids )
_lowerCamelCase : Optional[int] = tokenizer.batch_decode(out_sa.input_ids )
self.assertEqual(decode_s.split()[0] , SCREAMING_SNAKE_CASE_ )
self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) )
@slow
def _lowerCAmelCase ( self ):
_lowerCamelCase : Tuple = CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono' )
_lowerCamelCase : int = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#"""
_lowerCamelCase : str = """\nif len_a > len_b: result = a\nelse: result = b"""
_lowerCamelCase : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE_ )
_lowerCamelCase : int = ["""^#""", re.escape('<|endoftext|>' ), """^'''""", """^\"\"\"""", """\n\n\n"""]
_lowerCamelCase : Optional[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE_ , truncate_before_pattern=SCREAMING_SNAKE_CASE_ )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def _lowerCAmelCase ( self ):
pass
| 437 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
a : List[str] = logging.get_logger(__name__)
if is_vision_available():
import PIL
class _a ( _lowerCAmelCase ):
A = ['''pixel_values''']
def __init__(self, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = 1 / 255, SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = True, **SCREAMING_SNAKE_CASE_, ) -> None:
super().__init__(**SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Optional[Any] = size if size is not None else {"""shortest_edge""": 224}
UpperCAmelCase_: int = get_size_dict(SCREAMING_SNAKE_CASE_, default_to_square=SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Dict = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
UpperCAmelCase_: Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_, default_to_square=SCREAMING_SNAKE_CASE_, param_name="""crop_size""" )
UpperCAmelCase_: Optional[int] = do_resize
UpperCAmelCase_: Optional[int] = size
UpperCAmelCase_: Optional[int] = resample
UpperCAmelCase_: Tuple = do_center_crop
UpperCAmelCase_: Optional[int] = crop_size
UpperCAmelCase_: str = do_rescale
UpperCAmelCase_: Optional[int] = rescale_factor
UpperCAmelCase_: List[str] = do_normalize
UpperCAmelCase_: Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
UpperCAmelCase_: Dict = image_std if image_std is not None else OPENAI_CLIP_STD
UpperCAmelCase_: Any = do_convert_rgb
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> np.ndarray:
UpperCAmelCase_: Optional[Any] = get_size_dict(SCREAMING_SNAKE_CASE_, default_to_square=SCREAMING_SNAKE_CASE_ )
if "shortest_edge" not in size:
raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' )
UpperCAmelCase_: Optional[Any] = get_resize_output_image_size(SCREAMING_SNAKE_CASE_, size=size["""shortest_edge"""], default_to_square=SCREAMING_SNAKE_CASE_ )
return resize(SCREAMING_SNAKE_CASE_, size=SCREAMING_SNAKE_CASE_, resample=SCREAMING_SNAKE_CASE_, data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ )
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> np.ndarray:
UpperCAmelCase_: Any = get_size_dict(SCREAMING_SNAKE_CASE_ )
if "height" not in size or "width" not in size:
raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' )
return center_crop(SCREAMING_SNAKE_CASE_, size=(size["""height"""], size["""width"""]), data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ )
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> Union[str, Any]:
return rescale(SCREAMING_SNAKE_CASE_, scale=SCREAMING_SNAKE_CASE_, data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ )
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> np.ndarray:
return normalize(SCREAMING_SNAKE_CASE_, mean=SCREAMING_SNAKE_CASE_, std=SCREAMING_SNAKE_CASE_, data_format=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ )
def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST, **SCREAMING_SNAKE_CASE_, ) -> PIL.Image.Image:
UpperCAmelCase_: Tuple = do_resize if do_resize is not None else self.do_resize
UpperCAmelCase_: Tuple = size if size is not None else self.size
UpperCAmelCase_: str = get_size_dict(SCREAMING_SNAKE_CASE_, param_name="""size""", default_to_square=SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: List[str] = resample if resample is not None else self.resample
UpperCAmelCase_: Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop
UpperCAmelCase_: Tuple = crop_size if crop_size is not None else self.crop_size
UpperCAmelCase_: int = get_size_dict(SCREAMING_SNAKE_CASE_, param_name="""crop_size""", default_to_square=SCREAMING_SNAKE_CASE_ )
UpperCAmelCase_: Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale
UpperCAmelCase_: int = rescale_factor if rescale_factor is not None else self.rescale_factor
UpperCAmelCase_: Tuple = do_normalize if do_normalize is not None else self.do_normalize
UpperCAmelCase_: Dict = image_mean if image_mean is not None else self.image_mean
UpperCAmelCase_: int = image_std if image_std is not None else self.image_std
UpperCAmelCase_: Union[str, Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
UpperCAmelCase_: List[str] = make_list_of_images(SCREAMING_SNAKE_CASE_ )
if not valid_images(SCREAMING_SNAKE_CASE_ ):
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:
raise ValueError("""Size 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.""" )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
UpperCAmelCase_: Any = [convert_to_rgb(SCREAMING_SNAKE_CASE_ ) for image in images]
# All transformations expect numpy arrays.
UpperCAmelCase_: List[str] = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images]
if do_resize:
UpperCAmelCase_: str = [self.resize(image=SCREAMING_SNAKE_CASE_, size=SCREAMING_SNAKE_CASE_, resample=SCREAMING_SNAKE_CASE_ ) for image in images]
if do_center_crop:
UpperCAmelCase_: Dict = [self.center_crop(image=SCREAMING_SNAKE_CASE_, size=SCREAMING_SNAKE_CASE_ ) for image in images]
if do_rescale:
UpperCAmelCase_: Optional[Any] = [self.rescale(image=SCREAMING_SNAKE_CASE_, scale=SCREAMING_SNAKE_CASE_ ) for image in images]
if do_normalize:
UpperCAmelCase_: Dict = [self.normalize(image=SCREAMING_SNAKE_CASE_, mean=SCREAMING_SNAKE_CASE_, std=SCREAMING_SNAKE_CASE_ ) for image in images]
UpperCAmelCase_: Tuple = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) for image in images]
UpperCAmelCase_: Union[str, Any] = {"""pixel_values""": images}
return BatchFeature(data=SCREAMING_SNAKE_CASE_, tensor_type=SCREAMING_SNAKE_CASE_ )
| 556 | 0 |
'''simple docstring'''
import warnings
from ...utils import logging
from .image_processing_glpn import GLPNImageProcessor
_A = logging.get_logger(__name__)
class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ):
def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ):
warnings.warn(
"""The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"""
""" use GLPNImageProcessor instead.""" , _SCREAMING_SNAKE_CASE , )
super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) | 714 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from ..utils import cached_file
# docstyle-ignore
_A = '\nHuman: <<task>>\n\nAssistant: '
_A = 'huggingface-tools/default-prompts'
_A = {'chat': 'chat_prompt_template.txt', 'run': 'run_prompt_template.txt'}
def __SCREAMING_SNAKE_CASE ( UpperCamelCase : str , UpperCamelCase : Optional[int] , UpperCamelCase : Union[str, Any]="run" ) -> int:
"""simple docstring"""
if prompt_or_repo_id is None:
a_ = DEFAULT_PROMPTS_REPO
# prompt is considered a repo ID when it does not contain any kind of space
if re.search("""\\s""" , UpperCamelCase ) is not None:
return prompt_or_repo_id
a_ = cached_file(
UpperCamelCase , PROMPT_FILES[mode] , repo_type="""dataset""" , user_agent={"""agent""": agent_name} )
with open(UpperCamelCase , """r""" , encoding="""utf-8""" ) as f:
return f.read() | 403 | 0 |
"""simple docstring"""
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class _lowerCAmelCase ( lowerCamelCase ):
@staticmethod
@abstractmethod
def _a ( a_ ) -> Optional[int]:
raise NotImplementedError()
@abstractmethod
def _a ( self ) -> List[Any]:
raise NotImplementedError()
| 657 |
import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__a = logging.get_logger(__name__)
__a = '▁'
__a = {'vocab_file': 'vocab.txt', 'sentencepiece_model_ckpt': 'sentencepiece.bpe.model'}
__a = {
'sentencepiece_model_file': 'sentencepiece.bpe.model',
'vocab_file': 'vocab.txt',
}
__a = {
'vocab_file': {
'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
},
'sentencepiece_model_file': {
'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
},
}
__a = {
'ernie-m-base': 5_1_4,
'ernie-m-large': 5_1_4,
}
__a = {
'ernie-m-base': {'do_lower_case': False},
'ernie-m-large': {'do_lower_case': False},
}
class lowercase__( UpperCAmelCase ):
"""simple docstring"""
a :List[str] = ["input_ids"]
a :Dict = VOCAB_FILES_NAMES
a :Union[str, Any] = PRETRAINED_INIT_CONFIGURATION
a :Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a :List[str] = PRETRAINED_VOCAB_FILES_MAP
a :Tuple = RESOURCE_FILES_NAMES
def __init__( self : str , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : List[Any]=False , SCREAMING_SNAKE_CASE_ : Optional[Any]="utf8" , SCREAMING_SNAKE_CASE_ : List[Any]="[UNK]" , SCREAMING_SNAKE_CASE_ : Dict="[SEP]" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE_ : Optional[int]="[CLS]" , SCREAMING_SNAKE_CASE_ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE_ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE_ : Optional[int] , ) -> None:
# Mask token behave like a normal word, i.e. include the space before it and
# is included in the raw text, there should be a match in a non-normalized sentence.
lowercase_ = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , vocab_file=SCREAMING_SNAKE_CASE_ , encoding=SCREAMING_SNAKE_CASE_ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE_ , )
lowercase_ = do_lower_case
lowercase_ = sentencepiece_model_ckpt
lowercase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(SCREAMING_SNAKE_CASE_ )
# to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
if vocab_file is not None:
lowercase_ = self.load_vocab(filepath=SCREAMING_SNAKE_CASE_ )
else:
lowercase_ = {self.sp_model.id_to_piece(SCREAMING_SNAKE_CASE_ ): id for id in range(self.sp_model.get_piece_size() )}
lowercase_ = {v: k for k, v in self.vocab.items()}
def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : str ) -> List[Any]:
if text is None:
return None
lowercase_ = self.tokenize(SCREAMING_SNAKE_CASE_ )
lowercase_ , lowercase_ = '''''', []
for i, ch in enumerate(SCREAMING_SNAKE_CASE_ ):
if ch in self.SP_CHAR_MAPPING:
lowercase_ = self.SP_CHAR_MAPPING.get(SCREAMING_SNAKE_CASE_ )
else:
lowercase_ = unicodedata.normalize('''NFKC''' , SCREAMING_SNAKE_CASE_ )
if self.is_whitespace(SCREAMING_SNAKE_CASE_ ):
continue
normalized_text += ch
char_mapping.extend([i] * len(SCREAMING_SNAKE_CASE_ ) )
lowercase_ , lowercase_ , lowercase_ = normalized_text, [], 0
if self.do_lower_case:
lowercase_ = text.lower()
for token in split_tokens:
if token[:1] == "▁":
lowercase_ = token[1:]
lowercase_ = text[offset:].index(SCREAMING_SNAKE_CASE_ ) + offset
lowercase_ = start + len(SCREAMING_SNAKE_CASE_ )
token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) )
lowercase_ = end
return token_mapping
@property
def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]:
return len(self.vocab )
def _lowercase ( self : Any ) -> Optional[int]:
return dict(self.vocab , **self.added_tokens_encoder )
def __getstate__( self : Dict ) -> int:
lowercase_ = self.__dict__.copy()
lowercase_ = None
return state
def __setstate__( self : int , SCREAMING_SNAKE_CASE_ : Any ) -> List[Any]:
lowercase_ = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
lowercase_ = {}
lowercase_ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.sentencepiece_model_ckpt )
def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple ) -> str:
return "".join((self.SP_CHAR_MAPPING.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for c in text) )
def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any]=False , SCREAMING_SNAKE_CASE_ : Optional[int]=6_4 , SCREAMING_SNAKE_CASE_ : List[str]=0.1 ) -> Any:
if self.sp_model_kwargs.get('''enable_sampling''' ) is True:
lowercase_ = True
if self.sp_model_kwargs.get('''alpha''' ) is not None:
lowercase_ = self.sp_model_kwargs.get('''alpha''' )
if self.sp_model_kwargs.get('''nbest_size''' ) is not None:
lowercase_ = self.sp_model_kwargs.get('''nbest_size''' )
if not enable_sampling:
lowercase_ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE_ )
else:
lowercase_ = self.sp_model.SampleEncodeAsPieces(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
lowercase_ = []
for pi, piece in enumerate(SCREAMING_SNAKE_CASE_ ):
if piece == SPIECE_UNDERLINE:
if not pieces[pi + 1].startswith(SCREAMING_SNAKE_CASE_ ) and pi != 0:
new_pieces.append(SCREAMING_SNAKE_CASE_ )
continue
else:
continue
lowercase_ = 0
for i, chunk in enumerate(SCREAMING_SNAKE_CASE_ ):
if chunk == SPIECE_UNDERLINE:
continue
if self.is_ch_char(SCREAMING_SNAKE_CASE_ ) or self.is_punct(SCREAMING_SNAKE_CASE_ ):
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
new_pieces.append(SCREAMING_SNAKE_CASE_ )
lowercase_ = i + 1
elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
lowercase_ = i
elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
new_pieces.append(piece[lst_i:i] )
lowercase_ = i
if len(SCREAMING_SNAKE_CASE_ ) > lst_i:
new_pieces.append(piece[lst_i:] )
return new_pieces
def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : Any ) -> Optional[Any]:
lowercase_ = ''''''.join(SCREAMING_SNAKE_CASE_ ).replace(SCREAMING_SNAKE_CASE_ , ''' ''' ).strip()
return out_string
def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple ) -> Any:
lowercase_ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ )
lowercase_ = ''''''.join(SCREAMING_SNAKE_CASE_ ).replace(SCREAMING_SNAKE_CASE_ , ''' ''' ).strip()
return out_string
def _lowercase ( self : str , SCREAMING_SNAKE_CASE_ : List[str] ) -> List[str]:
return self.vocab.get(SCREAMING_SNAKE_CASE_ , self.vocab.get(self.unk_token ) )
def _lowercase ( self : str , SCREAMING_SNAKE_CASE_ : List[Any] ) -> List[Any]:
return self.reverse_vocab.get(SCREAMING_SNAKE_CASE_ , self.unk_token )
def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : str=None ) -> List[str]:
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
lowercase_ = [self.cls_token_id]
lowercase_ = [self.sep_token_id]
return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep
def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str]=None ) -> int:
if offset_mapping_a is None:
return [(0, 0)] + offset_mapping_a + [(0, 0)]
return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]
def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Optional[int]=False ) -> Any:
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
'''You should not supply a second sequence if the provided sequence of '''
'''ids is already formatted with special tokens for the model.''' )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1]
return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1]
def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : Optional[List[int]] = None ) -> List[int]:
# called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
if token_ids_a is None:
# [CLS] X [SEP]
return (len(SCREAMING_SNAKE_CASE_ ) + 2) * [0]
# [CLS] A [SEP] [SEP] B [SEP]
return [0] * (len(SCREAMING_SNAKE_CASE_ ) + 1) + [1] * (len(SCREAMING_SNAKE_CASE_ ) + 3)
def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[int]:
if "\u4e00" <= char <= "\u9fff":
return True
return False
def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Tuple:
if ("a" <= char <= "z") or ("A" <= char <= "Z"):
return True
return False
def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : int ) -> List[Any]:
if char in ",;:.?!~,;:。?!《》【】":
return True
return False
def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Union[str, Any]:
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
if len(SCREAMING_SNAKE_CASE_ ) == 1:
lowercase_ = unicodedata.category(SCREAMING_SNAKE_CASE_ )
if cat == "Zs":
return True
return False
def _lowercase ( self : Any , SCREAMING_SNAKE_CASE_ : Any ) -> Tuple:
lowercase_ = {}
with io.open(SCREAMING_SNAKE_CASE_ , '''r''' , encoding='''utf-8''' ) as f:
for index, line in enumerate(SCREAMING_SNAKE_CASE_ ):
lowercase_ = line.rstrip('''\n''' )
lowercase_ = int(SCREAMING_SNAKE_CASE_ )
return token_to_idx
def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[str] = None ) -> Tuple[str]:
lowercase_ = 0
if os.path.isdir(SCREAMING_SNAKE_CASE_ ):
lowercase_ = os.path.join(
SCREAMING_SNAKE_CASE_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
else:
lowercase_ = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
with open(SCREAMING_SNAKE_CASE_ , '''w''' , encoding='''utf-8''' ) as writer:
for token, token_index in sorted(self.vocab.items() , key=lambda SCREAMING_SNAKE_CASE_ : kv[1] ):
if index != token_index:
logger.warning(
f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
''' Please check that the vocabulary is not corrupted!''' )
lowercase_ = token_index
writer.write(token + '''\n''' )
index += 1
lowercase_ = os.path.join(SCREAMING_SNAKE_CASE_ , '''sentencepiece.bpe.model''' )
with open(SCREAMING_SNAKE_CASE_ , '''wb''' ) as fi:
lowercase_ = self.sp_model.serialized_model_proto()
fi.write(SCREAMING_SNAKE_CASE_ )
return (vocab_file,)
| 97 | 0 |
from __future__ import annotations
from collections import deque
class _UpperCAmelCase :
def __init__( self : List[str] , UpperCAmelCase : list[str]):
SCREAMING_SNAKE_CASE_ :list[dict] = []
self.adlist.append(
{"value": "", "next_states": [], "fail_state": 0, "output": []})
for keyword in keywords:
self.add_keyword(UpperCAmelCase)
self.set_fail_transitions()
def _snake_case ( self : int , UpperCAmelCase : int , UpperCAmelCase : str):
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None
def _snake_case ( self : List[Any] , UpperCAmelCase : str):
SCREAMING_SNAKE_CASE_ :Optional[int] = 0
for character in keyword:
SCREAMING_SNAKE_CASE_ :Any = self.find_next_state(UpperCAmelCase , UpperCAmelCase)
if next_state is None:
self.adlist.append(
{
"value": character,
"next_states": [],
"fail_state": 0,
"output": [],
})
self.adlist[current_state]["next_states"].append(len(self.adlist) - 1)
SCREAMING_SNAKE_CASE_ :Union[str, Any] = len(self.adlist) - 1
else:
SCREAMING_SNAKE_CASE_ :Dict = next_state
self.adlist[current_state]["output"].append(UpperCAmelCase)
def _snake_case ( self : Dict):
SCREAMING_SNAKE_CASE_ :deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :Any = 0
while q:
SCREAMING_SNAKE_CASE_ :int = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(UpperCAmelCase)
SCREAMING_SNAKE_CASE_ :List[Any] = self.adlist[r]["fail_state"]
while (
self.find_next_state(UpperCAmelCase , self.adlist[child]["value"]) is None
and state != 0
):
SCREAMING_SNAKE_CASE_ :List[str] = self.adlist[state]["fail_state"]
SCREAMING_SNAKE_CASE_ :Optional[int] = self.find_next_state(
UpperCAmelCase , self.adlist[child]["value"])
if self.adlist[child]["fail_state"] is None:
SCREAMING_SNAKE_CASE_ :int = 0
SCREAMING_SNAKE_CASE_ :Optional[Any] = (
self.adlist[child]["output"]
+ self.adlist[self.adlist[child]["fail_state"]]["output"]
)
def _snake_case ( self : Dict , UpperCAmelCase : str):
SCREAMING_SNAKE_CASE_ :dict = {} # returns a dict with keywords and list of its occurrences
SCREAMING_SNAKE_CASE_ :Optional[int] = 0
for i in range(len(UpperCAmelCase)):
while (
self.find_next_state(UpperCAmelCase , string[i]) is None
and current_state != 0
):
SCREAMING_SNAKE_CASE_ :int = self.adlist[current_state]["fail_state"]
SCREAMING_SNAKE_CASE_ :int = self.find_next_state(UpperCAmelCase , string[i])
if next_state is None:
SCREAMING_SNAKE_CASE_ :Dict = 0
else:
SCREAMING_SNAKE_CASE_ :str = next_state
for key in self.adlist[current_state]["output"]:
if key not in result:
SCREAMING_SNAKE_CASE_ :List[Any] = []
result[key].append(i - len(UpperCAmelCase) + 1)
return result
if __name__ == "__main__":
import doctest
doctest.testmod() | 706 |
from itertools import product
from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey
from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros
def lowercase ( a , a ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :Optional[int] = k_size // 2
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :List[str] = mgrid[0 - center : k_size - center, 0 - center : k_size - center]
SCREAMING_SNAKE_CASE_ :Optional[Any] = 1 / (2 * pi * sigma) * exp(-(square(a ) + square(a )) / (2 * square(a )) )
return g
def lowercase ( a , a , a ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :str = image.shape[0], image.shape[1]
# dst image height and width
SCREAMING_SNAKE_CASE_ :Optional[int] = height - k_size + 1
SCREAMING_SNAKE_CASE_ :Any = width - k_size + 1
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
SCREAMING_SNAKE_CASE_ :Any = zeros((dst_height * dst_width, k_size * k_size) )
SCREAMING_SNAKE_CASE_ :List[str] = 0
for i, j in product(range(a ) , range(a ) ):
SCREAMING_SNAKE_CASE_ :Union[str, Any] = ravel(image[i : i + k_size, j : j + k_size] )
SCREAMING_SNAKE_CASE_ :Dict = window
row += 1
# turn the kernel into shape(k*k, 1)
SCREAMING_SNAKE_CASE_ :Tuple = gen_gaussian_kernel(a , a )
SCREAMING_SNAKE_CASE_ :List[Any] = ravel(a )
# reshape and get the dst image
SCREAMING_SNAKE_CASE_ :Dict = dot(a , a ).reshape(a , a ).astype(a )
return dst
if __name__ == "__main__":
# read original image
SCREAMING_SNAKE_CASE__ = imread(R"../image_data/lena.jpg")
# turn image in gray scale value
SCREAMING_SNAKE_CASE__ = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
SCREAMING_SNAKE_CASE__ = gaussian_filter(gray, 3, sigma=1)
SCREAMING_SNAKE_CASE__ = gaussian_filter(gray, 5, sigma=0.8)
# show result images
imshow("gaussian filter with 3x3 mask", gaussianaxa)
imshow("gaussian filter with 5x5 mask", gaussianaxa)
waitKey()
| 140 | 0 |
from __future__ import annotations
__A : List[str] = {
"A": ["B", "C", "E"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
class lowerCamelCase:
'''simple docstring'''
def __init__( self , snake_case_ , snake_case_ ):
_A = graph
# mapping node to its parent in resulting breadth first tree
_A = {}
_A = source_vertex
def lowerCAmelCase__ ( self ):
_A = {self.source_vertex}
_A = None
_A = [self.source_vertex] # first in first out queue
while queue:
_A = queue.pop(0 )
for adjacent_vertex in self.graph[vertex]:
if adjacent_vertex not in visited:
visited.add(snake_case_ )
_A = vertex
queue.append(snake_case_ )
def lowerCAmelCase__ ( self , snake_case_ ):
if target_vertex == self.source_vertex:
return self.source_vertex
_A = self.parent.get(snake_case_ )
if target_vertex_parent is None:
_A = (
F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}"
)
raise ValueError(snake_case_ )
return self.shortest_path(snake_case_ ) + F"->{target_vertex}"
if __name__ == "__main__":
__A : Optional[int] = Graph(graph, "G")
g.breath_first_search()
print(g.shortest_path("D"))
print(g.shortest_path("G"))
print(g.shortest_path("Foo"))
| 27 |
'''simple docstring'''
from math import pow
def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, ) -> tuple[int, int]:
if current_sum == needed_sum:
# If the sum of the powers is equal to needed_sum, then we have a solution.
solutions_count += 1
return current_sum, solutions_count
A_ = int(pow(UpperCAmelCase__, UpperCAmelCase__ ) )
if current_sum + i_to_n <= needed_sum:
# If the sum of the powers is less than needed_sum, then continue adding powers.
current_sum += i_to_n
A_ , A_ = backtrack(
UpperCAmelCase__, UpperCAmelCase__, current_number + 1, UpperCAmelCase__, UpperCAmelCase__ )
current_sum -= i_to_n
if i_to_n < needed_sum:
# If the power of i is less than needed_sum, then try with the next power.
A_ , A_ = backtrack(
UpperCAmelCase__, UpperCAmelCase__, current_number + 1, UpperCAmelCase__, UpperCAmelCase__ )
return current_sum, solutions_count
def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__ ) -> int:
if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10):
raise ValueError(
"""Invalid input\n"""
"""needed_sum must be between 1 and 1000, power between 2 and 10.""" )
return backtrack(UpperCAmelCase__, UpperCAmelCase__, 1, 0, 0 )[1] # Return the solutions_count
if __name__ == "__main__":
import doctest
doctest.testmod()
| 288 | 0 |
from __future__ import annotations
from decimal import Decimal
from math import * # noqa: F403
from sympy import diff
def __UpperCAmelCase ( __a : str ,__a : float | Decimal ,__a : float = 10**-10 ) -> float:
"""simple docstring"""
_a : Optional[int] = a
while True:
_a : List[str] = Decimal(__a ) - (
Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307
)
# This number dictates the accuracy of the answer
if abs(eval(__a ) ) < precision: # noqa: S307
return float(__a )
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(f'''The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}''')
# Find root of polynomial
print(f'''The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}''')
# Find Square Root of 5
print(f'''The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}''')
# Exponential Roots
print(f'''The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}''')
| 718 |
def __UpperCAmelCase ( __a : int = 2_000_000 ) -> int:
"""simple docstring"""
_a : List[str] = [0 for i in range(n + 1 )]
_a : Tuple = 1
_a : Tuple = 1
for i in range(2 ,int(n**0.5 ) + 1 ):
if primality_list[i] == 0:
for j in range(i * i ,n + 1 ,__a ):
_a : List[str] = 1
_a : List[Any] = 0
for i in range(__a ):
if primality_list[i] == 0:
sum_of_primes += i
return sum_of_primes
if __name__ == "__main__":
print(f'''{solution() = }''')
| 578 | 0 |
"""simple docstring"""
def a_ ( lowercase__ :Union[str, Any], lowercase__ :int ):
return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2
def a_ ( lowercase__ :List[Any], lowercase__ :List[str]=0 ):
return sorted(lowercase__, key=lambda lowercase__ : x[column] )
def a_ ( lowercase__ :Union[str, Any], lowercase__ :str, lowercase__ :Tuple=float("""inf""" ) ):
for i in range(points_counts - 1 ):
for j in range(i + 1, lowercase__ ):
__lowerCamelCase = euclidean_distance_sqr(points[i], points[j] )
if current_dis < min_dis:
__lowerCamelCase = current_dis
return min_dis
def a_ ( lowercase__ :str, lowercase__ :Optional[int], lowercase__ :Union[str, Any]=float("""inf""" ) ):
for i in range(min(6, points_counts - 1 ), lowercase__ ):
for j in range(max(0, i - 6 ), lowercase__ ):
__lowerCamelCase = euclidean_distance_sqr(points[i], points[j] )
if current_dis < min_dis:
__lowerCamelCase = current_dis
return min_dis
def a_ ( lowercase__ :List[Any], lowercase__ :List[str], lowercase__ :int ):
# base case
if points_counts <= 3:
return dis_between_closest_pair(lowercase__, lowercase__ )
# recursion
__lowerCamelCase = points_counts // 2
__lowerCamelCase = closest_pair_of_points_sqr(
lowercase__, points_sorted_on_y[:mid], lowercase__ )
__lowerCamelCase = closest_pair_of_points_sqr(
lowercase__, points_sorted_on_y[mid:], points_counts - mid )
__lowerCamelCase = min(lowercase__, lowercase__ )
__lowerCamelCase = []
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis:
cross_strip.append(lowercase__ )
__lowerCamelCase = dis_between_closest_in_strip(
lowercase__, len(lowercase__ ), lowercase__ )
return min(lowercase__, lowercase__ )
def a_ ( lowercase__ :List[Any], lowercase__ :int ):
__lowerCamelCase = column_based_sort(lowercase__, column=0 )
__lowerCamelCase = column_based_sort(lowercase__, column=1 )
return (
closest_pair_of_points_sqr(
lowercase__, lowercase__, lowercase__ )
) ** 0.5
if __name__ == "__main__":
__magic_name__ : Union[str, Any] = [(2, 3), (1_2, 3_0), (4_0, 5_0), (5, 1), (1_2, 1_0), (3, 4)]
print('Distance:', closest_pair_of_points(points, len(points)))
| 281 |
"""simple docstring"""
import math
from typing import Optional
import numpy as np
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__magic_name__ : List[str] = logging.get_logger(__name__)
__magic_name__ : Tuple = {
'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json',
'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json',
}
class __snake_case (lowerCamelCase ):
__a = '''encodec'''
def __init__( self: Union[str, Any] , A_: Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , A_: Any=2_40_00 , A_: List[Any]=1 , A_: Optional[Any]=False , A_: Optional[int]=None , A_: int=None , A_: List[str]=1_28 , A_: Union[str, Any]=32 , A_: List[str]=1 , A_: Dict=[8, 5, 4, 2] , A_: List[Any]="weight_norm" , A_: Any=7 , A_: List[Any]=7 , A_: Tuple=3 , A_: List[str]=2 , A_: Optional[Any]=True , A_: Optional[int]="reflect" , A_: Dict=2 , A_: Union[str, Any]=2 , A_: Union[str, Any]=1.0 , A_: List[str]=10_24 , A_: str=None , A_: List[str]=True , **A_: int , ):
__lowerCamelCase = target_bandwidths
__lowerCamelCase = sampling_rate
__lowerCamelCase = audio_channels
__lowerCamelCase = normalize
__lowerCamelCase = chunk_length_s
__lowerCamelCase = overlap
__lowerCamelCase = hidden_size
__lowerCamelCase = num_filters
__lowerCamelCase = num_residual_layers
__lowerCamelCase = upsampling_ratios
__lowerCamelCase = norm_type
__lowerCamelCase = kernel_size
__lowerCamelCase = last_kernel_size
__lowerCamelCase = residual_kernel_size
__lowerCamelCase = dilation_growth_rate
__lowerCamelCase = use_causal_conv
__lowerCamelCase = pad_mode
__lowerCamelCase = compress
__lowerCamelCase = num_lstm_layers
__lowerCamelCase = trim_right_ratio
__lowerCamelCase = codebook_size
__lowerCamelCase = codebook_dim if codebook_dim is not None else hidden_size
__lowerCamelCase = use_conv_shortcut
if self.norm_type not in ["weight_norm", "time_group_norm"]:
raise ValueError(
f'self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}' )
super().__init__(**A_ )
@property
def __a ( self: Union[str, Any] ):
if self.chunk_length_s is None:
return None
else:
return int(self.chunk_length_s * self.sampling_rate )
@property
def __a ( self: List[Any] ):
if self.chunk_length_s is None or self.overlap is None:
return None
else:
return max(1 , int((1.0 - self.overlap) * self.chunk_length ) )
@property
def __a ( self: List[Any] ):
__lowerCamelCase = np.prod(self.upsampling_ratios )
return math.ceil(self.sampling_rate / hop_length )
@property
def __a ( self: List[Any] ):
return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
| 281 | 1 |
import argparse
from typing import List
import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset
# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
lowerCamelCase__ = 16
lowerCamelCase__ = 32
def lowercase_ ( SCREAMING_SNAKE_CASE : Accelerator , SCREAMING_SNAKE_CASE : DatasetDict , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : int = 16 ):
"""simple docstring"""
snake_case__ : int =AutoTokenizer.from_pretrained('''bert-base-cased''' )
snake_case__ : Dict =DatasetDict(
{
'''train''': dataset['''train'''].select(SCREAMING_SNAKE_CASE ),
'''validation''': dataset['''train'''].select(SCREAMING_SNAKE_CASE ),
'''test''': dataset['''validation'''],
} )
def tokenize_function(SCREAMING_SNAKE_CASE : Union[str, Any] ):
# max_length=None => use the model max length (it's actually the default)
snake_case__ : Dict =tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
snake_case__ : Union[str, Any] =datasets.map(
SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
snake_case__ : List[Any] =tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(SCREAMING_SNAKE_CASE : List[Any] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
snake_case__ : Tuple =1_28 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
snake_case__ : Optional[int] =16
elif accelerator.mixed_precision != "no":
snake_case__ : Tuple =8
else:
snake_case__ : Union[str, Any] =None
return tokenizer.pad(
SCREAMING_SNAKE_CASE , padding='''longest''' , max_length=SCREAMING_SNAKE_CASE , pad_to_multiple_of=SCREAMING_SNAKE_CASE , return_tensors='''pt''' , )
# Instantiate dataloaders.
snake_case__ : List[str] =DataLoader(
tokenized_datasets['''train'''] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
snake_case__ : List[str] =DataLoader(
tokenized_datasets['''validation'''] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
snake_case__ : Optional[int] =DataLoader(
tokenized_datasets['''test'''] , shuffle=SCREAMING_SNAKE_CASE , collate_fn=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE )
return train_dataloader, eval_dataloader, test_dataloader
def lowercase_ ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
# New Code #
snake_case__ : str =[]
# Download the dataset
snake_case__ : Union[str, Any] =load_dataset('''glue''' , '''mrpc''' )
# Create our splits
snake_case__ : int =StratifiedKFold(n_splits=int(args.num_folds ) )
# Initialize accelerator
snake_case__ : List[Any] =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
snake_case__ : str =config['''lr''']
snake_case__ : List[str] =int(config['''num_epochs'''] )
snake_case__ : int =int(config['''seed'''] )
snake_case__ : Optional[int] =int(config['''batch_size'''] )
snake_case__ : List[str] =evaluate.load('''glue''' , '''mrpc''' )
# If the batch size is too big we use gradient accumulation
snake_case__ : str =1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
snake_case__ : Tuple =batch_size // MAX_GPU_BATCH_SIZE
snake_case__ : int =MAX_GPU_BATCH_SIZE
set_seed(SCREAMING_SNAKE_CASE )
# New Code #
# Create our folds:
snake_case__ : Union[str, Any] =kfold.split(np.zeros(datasets['''train'''].num_rows ) , datasets['''train''']['''label'''] )
snake_case__ : Dict =[]
# Iterate over them
for i, (train_idxs, valid_idxs) in enumerate(SCREAMING_SNAKE_CASE ):
snake_case__, snake_case__, snake_case__ : Optional[Any] =get_fold_dataloaders(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
snake_case__ : Optional[int] =AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=SCREAMING_SNAKE_CASE )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
snake_case__ : List[str] =model.to(accelerator.device )
# Instantiate optimizer
snake_case__ : Optional[int] =AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE )
# Instantiate scheduler
snake_case__ : int =get_linear_schedule_with_warmup(
optimizer=SCREAMING_SNAKE_CASE , num_warmup_steps=1_00 , num_training_steps=(len(SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
snake_case__, snake_case__, snake_case__, snake_case__, snake_case__ : Union[str, Any] =accelerator.prepare(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
# Now we train the model
for epoch in range(SCREAMING_SNAKE_CASE ):
model.train()
for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
snake_case__ : List[str] =model(**SCREAMING_SNAKE_CASE )
snake_case__ : List[Any] =outputs.loss
snake_case__ : Union[str, Any] =loss / gradient_accumulation_steps
accelerator.backward(SCREAMING_SNAKE_CASE )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
snake_case__ : str =model(**SCREAMING_SNAKE_CASE )
snake_case__ : Union[str, Any] =outputs.logits.argmax(dim=-1 )
snake_case__, snake_case__ : Any =accelerator.gather_for_metrics((predictions, batch['''labels''']) )
metric.add_batch(
predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE , )
snake_case__ : Tuple =metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F'''epoch {epoch}:''' , SCREAMING_SNAKE_CASE )
# New Code #
# We also run predictions on the test set at the very end
snake_case__ : List[str] =[]
for step, batch in enumerate(SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
snake_case__ : Any =model(**SCREAMING_SNAKE_CASE )
snake_case__ : Optional[int] =outputs.logits
snake_case__, snake_case__ : Union[str, Any] =accelerator.gather_for_metrics((predictions, batch['''labels''']) )
fold_predictions.append(predictions.cpu() )
if i == 0:
# We need all of the test predictions
test_references.append(references.cpu() )
# Use accelerator.print to print only on the main process.
test_predictions.append(torch.cat(SCREAMING_SNAKE_CASE , dim=0 ) )
# We now need to release all our memory and get rid of the current model, optimizer, etc
accelerator.free_memory()
# New Code #
# Finally we check the accuracy of our folded results:
snake_case__ : Any =torch.cat(SCREAMING_SNAKE_CASE , dim=0 )
snake_case__ : List[str] =torch.stack(SCREAMING_SNAKE_CASE , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 )
snake_case__ : Any =metric.compute(predictions=SCREAMING_SNAKE_CASE , references=SCREAMING_SNAKE_CASE )
accelerator.print('''Average test metrics from all folds:''' , SCREAMING_SNAKE_CASE )
def lowercase_ ( ):
"""simple docstring"""
snake_case__ : Tuple =argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument(
'''--mixed_precision''' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''' , )
parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' )
# New Code #
parser.add_argument('''--num_folds''' , type=SCREAMING_SNAKE_CASE , default=3 , help='''The number of splits to perform across the dataset''' )
snake_case__ : Dict =parser.parse_args()
snake_case__ : str ={'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 408 |
def lowercase_ ( SCREAMING_SNAKE_CASE : int = 60_08_51_47_51_43 ):
"""simple docstring"""
try:
snake_case__ : Any =int(SCREAMING_SNAKE_CASE )
except (TypeError, ValueError):
raise TypeError('''Parameter n must be int or castable to int.''' )
if n <= 0:
raise ValueError('''Parameter n must be greater than or equal to one.''' )
snake_case__ : Any =1
snake_case__ : List[str] =2
while i * i <= n:
while n % i == 0:
snake_case__ : Union[str, Any] =i
n //= i
i += 1
if n > 1:
snake_case__ : Any =n
return int(SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 408 | 1 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__UpperCamelCase = {
"configuration_roberta": ["ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaConfig", "RobertaOnnxConfig"],
"tokenization_roberta": ["RobertaTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase = ["RobertaTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase = [
"ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST",
"RobertaForCausalLM",
"RobertaForMaskedLM",
"RobertaForMultipleChoice",
"RobertaForQuestionAnswering",
"RobertaForSequenceClassification",
"RobertaForTokenClassification",
"RobertaModel",
"RobertaPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase = [
"TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFRobertaForCausalLM",
"TFRobertaForMaskedLM",
"TFRobertaForMultipleChoice",
"TFRobertaForQuestionAnswering",
"TFRobertaForSequenceClassification",
"TFRobertaForTokenClassification",
"TFRobertaMainLayer",
"TFRobertaModel",
"TFRobertaPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase = [
"FlaxRobertaForCausalLM",
"FlaxRobertaForMaskedLM",
"FlaxRobertaForMultipleChoice",
"FlaxRobertaForQuestionAnswering",
"FlaxRobertaForSequenceClassification",
"FlaxRobertaForTokenClassification",
"FlaxRobertaModel",
"FlaxRobertaPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig
from .tokenization_roberta import RobertaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_roberta_fast import RobertaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_roberta import (
ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
RobertaForCausalLM,
RobertaForMaskedLM,
RobertaForMultipleChoice,
RobertaForQuestionAnswering,
RobertaForSequenceClassification,
RobertaForTokenClassification,
RobertaModel,
RobertaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_roberta import (
TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFRobertaForCausalLM,
TFRobertaForMaskedLM,
TFRobertaForMultipleChoice,
TFRobertaForQuestionAnswering,
TFRobertaForSequenceClassification,
TFRobertaForTokenClassification,
TFRobertaMainLayer,
TFRobertaModel,
TFRobertaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_roberta import (
FlaxRobertaForCausalLM,
FlaxRobertaForMaskedLM,
FlaxRobertaForMultipleChoice,
FlaxRobertaForQuestionAnswering,
FlaxRobertaForSequenceClassification,
FlaxRobertaForTokenClassification,
FlaxRobertaModel,
FlaxRobertaPreTrainedModel,
)
else:
import sys
__UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 26 |
'''simple docstring'''
# Usage:
# ./gen-card-facebook-wmt19.py
import os
from pathlib import Path
def SCREAMING_SNAKE_CASE ( a_ : str , a_ : Union[str, Any] , a_ : Dict ):
__a = {
'en': 'Machine learning is great, isn\'t it?',
'ru': 'Машинное обучение - это здорово, не так ли?',
'de': 'Maschinelles Lernen ist großartig, oder?',
}
# BLUE scores as follows:
# "pair": [fairseq, transformers]
__a = {
'ru-en': ['[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)', '39.20'],
'en-ru': ['[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)', '33.47'],
'en-de': ['[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)', '42.83'],
'de-en': ['[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)', '41.35'],
}
__a = f"{src_lang}-{tgt_lang}"
__a = f"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n"
os.makedirs(a_ , exist_ok=a_ )
__a = os.path.join(a_ , 'README.md' )
print(f"Generating {path}" )
with open(a_ , 'w' , encoding='utf-8' ) as f:
f.write(a_ )
# make sure we are under the root of the project
UpperCAmelCase_ = Path(__file__).resolve().parent.parent.parent
UpperCAmelCase_ = repo_dir / "model_cards"
for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = model_name.split("-")
UpperCAmelCase_ = model_cards_dir / "facebook" / model_name
write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
| 539 | 0 |
"""simple docstring"""
import hashlib
import unittest
from typing import Dict
import numpy as np
from transformers import (
MODEL_FOR_MASK_GENERATION_MAPPING,
TF_MODEL_FOR_MASK_GENERATION_MAPPING,
is_vision_available,
pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
if is_vision_available():
from PIL import Image
else:
class a :
@staticmethod
def __snake_case ( *UpperCamelCase_ , **UpperCamelCase_ ):
pass
def lowerCamelCase ( _snake_case ):
UpperCAmelCase__ : Any = hashlib.mda(image.tobytes() )
return m.hexdigest()[:10]
def lowerCamelCase ( _snake_case ):
UpperCAmelCase__ : int = np.array(_snake_case )
UpperCAmelCase__ : Any = npimg.shape
return {"hash": hashimage(_snake_case ), "shape": shape}
@is_pipeline_test
@require_vision
@require_torch
class a ( unittest.TestCase ):
UpperCamelCase : Dict = dict(
(list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) )
UpperCamelCase : str = dict(
(list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) )
def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ):
UpperCAmelCase__ : int = MaskGenerationPipeline(model=UpperCamelCase_ , image_processor=UpperCamelCase_ )
return image_segmenter, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ ):
pass
@require_tf
@unittest.skip('Image segmentation not implemented in TF' )
def __snake_case ( self ):
pass
@slow
@require_torch
def __snake_case ( self ):
UpperCAmelCase__ : Any = pipeline('mask-generation' , model='facebook/sam-vit-huge' )
UpperCAmelCase__ : int = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 )
# Shortening by hashing
UpperCAmelCase__ : Optional[int] = []
for i, o in enumerate(outputs['masks'] ):
new_outupt += [{"mask": mask_to_test_readable(UpperCamelCase_ ), "scores": outputs["scores"][i]}]
# fmt: off
self.assertEqual(
nested_simplify(UpperCamelCase_ , decimals=4 ) , [
{'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0444},
{'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.021},
{'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0167},
{'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0132},
{'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0053},
{'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9967},
{'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.993},
{'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9909},
{'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9879},
{'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9834},
{'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9716},
{'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9612},
{'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9599},
{'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9552},
{'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9532},
{'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9516},
{'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9499},
{'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9483},
{'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9464},
{'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.943},
{'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.943},
{'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9408},
{'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9335},
{'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9326},
{'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9262},
{'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8999},
{'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8986},
{'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8984},
{'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8873},
{'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8871}
] , )
# fmt: on
@require_torch
@slow
def __snake_case ( self ):
UpperCAmelCase__ : List[Any] = 'facebook/sam-vit-huge'
UpperCAmelCase__ : Union[str, Any] = pipeline('mask-generation' , model=UpperCamelCase_ )
UpperCAmelCase__ : str = image_segmenter(
'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 )
# Shortening by hashing
UpperCAmelCase__ : Union[str, Any] = []
for i, o in enumerate(outputs['masks'] ):
new_outupt += [{"mask": mask_to_test_readable(UpperCamelCase_ ), "scores": outputs["scores"][i]}]
self.assertEqual(
nested_simplify(UpperCamelCase_ , decimals=4 ) , [
{'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0444},
{'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0210},
{'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0167},
{'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0132},
{'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0053},
] , )
| 254 |
"""simple docstring"""
import cva
import numpy as np
class a :
def __init__( self , UpperCamelCase_ , UpperCamelCase_ ):
if k in (0.04, 0.06):
UpperCAmelCase__ : List[str] = k
UpperCAmelCase__ : str = window_size
else:
raise ValueError('invalid k value' )
def __str__( self ):
return str(self.k )
def __snake_case ( self , UpperCamelCase_ ):
UpperCAmelCase__ : int = cva.imread(UpperCamelCase_ , 0 )
UpperCAmelCase__ , UpperCAmelCase__ : int = img.shape
UpperCAmelCase__ : list[list[int]] = []
UpperCAmelCase__ : Dict = img.copy()
UpperCAmelCase__ : Dict = cva.cvtColor(UpperCamelCase_ , cva.COLOR_GRAY2RGB )
UpperCAmelCase__ , UpperCAmelCase__ : Dict = np.gradient(UpperCamelCase_ )
UpperCAmelCase__ : List[str] = dx**2
UpperCAmelCase__ : List[Any] = dy**2
UpperCAmelCase__ : List[str] = dx * dy
UpperCAmelCase__ : Optional[int] = 0.04
UpperCAmelCase__ : List[str] = self.window_size // 2
for y in range(UpperCamelCase_ , h - offset ):
for x in range(UpperCamelCase_ , w - offset ):
UpperCAmelCase__ : Optional[int] = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
UpperCAmelCase__ : Tuple = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
UpperCAmelCase__ : Any = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
UpperCAmelCase__ : Optional[Any] = (wxx * wyy) - (wxy**2)
UpperCAmelCase__ : Optional[int] = wxx + wyy
UpperCAmelCase__ : Tuple = det - k * (trace**2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r] )
color_img.itemset((y, x, 0) , 0 )
color_img.itemset((y, x, 1) , 0 )
color_img.itemset((y, x, 2) , 255 )
return color_img, corner_list
if __name__ == "__main__":
UpperCamelCase__ = HarrisCorner(0.04, 3)
UpperCamelCase__ , UpperCamelCase__ = edge_detect.detect('path_to_image')
cva.imwrite('detect.png', color_img)
| 254 | 1 |
from collections import OrderedDict
from ...utils import logging
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
from .configuration_auto import CONFIG_MAPPING_NAMES
UpperCAmelCase_ = logging.get_logger(__name__)
UpperCAmelCase_ = OrderedDict(
[
# Base model mapping
("albert", "FlaxAlbertModel"),
("bart", "FlaxBartModel"),
("beit", "FlaxBeitModel"),
("bert", "FlaxBertModel"),
("big_bird", "FlaxBigBirdModel"),
("blenderbot", "FlaxBlenderbotModel"),
("blenderbot-small", "FlaxBlenderbotSmallModel"),
("clip", "FlaxCLIPModel"),
("distilbert", "FlaxDistilBertModel"),
("electra", "FlaxElectraModel"),
("gpt-sw3", "FlaxGPT2Model"),
("gpt2", "FlaxGPT2Model"),
("gpt_neo", "FlaxGPTNeoModel"),
("gptj", "FlaxGPTJModel"),
("longt5", "FlaxLongT5Model"),
("marian", "FlaxMarianModel"),
("mbart", "FlaxMBartModel"),
("mt5", "FlaxMT5Model"),
("opt", "FlaxOPTModel"),
("pegasus", "FlaxPegasusModel"),
("regnet", "FlaxRegNetModel"),
("resnet", "FlaxResNetModel"),
("roberta", "FlaxRobertaModel"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"),
("roformer", "FlaxRoFormerModel"),
("t5", "FlaxT5Model"),
("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"),
("vit", "FlaxViTModel"),
("wav2vec2", "FlaxWav2Vec2Model"),
("whisper", "FlaxWhisperModel"),
("xglm", "FlaxXGLMModel"),
("xlm-roberta", "FlaxXLMRobertaModel"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for pre-training mapping
("albert", "FlaxAlbertForPreTraining"),
("bart", "FlaxBartForConditionalGeneration"),
("bert", "FlaxBertForPreTraining"),
("big_bird", "FlaxBigBirdForPreTraining"),
("electra", "FlaxElectraForPreTraining"),
("longt5", "FlaxLongT5ForConditionalGeneration"),
("mbart", "FlaxMBartForConditionalGeneration"),
("mt5", "FlaxMT5ForConditionalGeneration"),
("roberta", "FlaxRobertaForMaskedLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
("roformer", "FlaxRoFormerForMaskedLM"),
("t5", "FlaxT5ForConditionalGeneration"),
("wav2vec2", "FlaxWav2Vec2ForPreTraining"),
("whisper", "FlaxWhisperForConditionalGeneration"),
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Masked LM mapping
("albert", "FlaxAlbertForMaskedLM"),
("bart", "FlaxBartForConditionalGeneration"),
("bert", "FlaxBertForMaskedLM"),
("big_bird", "FlaxBigBirdForMaskedLM"),
("distilbert", "FlaxDistilBertForMaskedLM"),
("electra", "FlaxElectraForMaskedLM"),
("mbart", "FlaxMBartForConditionalGeneration"),
("roberta", "FlaxRobertaForMaskedLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
("roformer", "FlaxRoFormerForMaskedLM"),
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Seq2Seq Causal LM mapping
("bart", "FlaxBartForConditionalGeneration"),
("blenderbot", "FlaxBlenderbotForConditionalGeneration"),
("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"),
("encoder-decoder", "FlaxEncoderDecoderModel"),
("longt5", "FlaxLongT5ForConditionalGeneration"),
("marian", "FlaxMarianMTModel"),
("mbart", "FlaxMBartForConditionalGeneration"),
("mt5", "FlaxMT5ForConditionalGeneration"),
("pegasus", "FlaxPegasusForConditionalGeneration"),
("t5", "FlaxT5ForConditionalGeneration"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Image-classsification
("beit", "FlaxBeitForImageClassification"),
("regnet", "FlaxRegNetForImageClassification"),
("resnet", "FlaxResNetForImageClassification"),
("vit", "FlaxViTForImageClassification"),
]
)
UpperCAmelCase_ = OrderedDict(
[
("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Causal LM mapping
("bart", "FlaxBartForCausalLM"),
("bert", "FlaxBertForCausalLM"),
("big_bird", "FlaxBigBirdForCausalLM"),
("electra", "FlaxElectraForCausalLM"),
("gpt-sw3", "FlaxGPT2LMHeadModel"),
("gpt2", "FlaxGPT2LMHeadModel"),
("gpt_neo", "FlaxGPTNeoForCausalLM"),
("gptj", "FlaxGPTJForCausalLM"),
("opt", "FlaxOPTForCausalLM"),
("roberta", "FlaxRobertaForCausalLM"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"),
("xglm", "FlaxXGLMForCausalLM"),
("xlm-roberta", "FlaxXLMRobertaForCausalLM"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Sequence Classification mapping
("albert", "FlaxAlbertForSequenceClassification"),
("bart", "FlaxBartForSequenceClassification"),
("bert", "FlaxBertForSequenceClassification"),
("big_bird", "FlaxBigBirdForSequenceClassification"),
("distilbert", "FlaxDistilBertForSequenceClassification"),
("electra", "FlaxElectraForSequenceClassification"),
("mbart", "FlaxMBartForSequenceClassification"),
("roberta", "FlaxRobertaForSequenceClassification"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"),
("roformer", "FlaxRoFormerForSequenceClassification"),
("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Question Answering mapping
("albert", "FlaxAlbertForQuestionAnswering"),
("bart", "FlaxBartForQuestionAnswering"),
("bert", "FlaxBertForQuestionAnswering"),
("big_bird", "FlaxBigBirdForQuestionAnswering"),
("distilbert", "FlaxDistilBertForQuestionAnswering"),
("electra", "FlaxElectraForQuestionAnswering"),
("mbart", "FlaxMBartForQuestionAnswering"),
("roberta", "FlaxRobertaForQuestionAnswering"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"),
("roformer", "FlaxRoFormerForQuestionAnswering"),
("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Token Classification mapping
("albert", "FlaxAlbertForTokenClassification"),
("bert", "FlaxBertForTokenClassification"),
("big_bird", "FlaxBigBirdForTokenClassification"),
("distilbert", "FlaxDistilBertForTokenClassification"),
("electra", "FlaxElectraForTokenClassification"),
("roberta", "FlaxRobertaForTokenClassification"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"),
("roformer", "FlaxRoFormerForTokenClassification"),
("xlm-roberta", "FlaxXLMRobertaForTokenClassification"),
]
)
UpperCAmelCase_ = OrderedDict(
[
# Model for Multiple Choice mapping
("albert", "FlaxAlbertForMultipleChoice"),
("bert", "FlaxBertForMultipleChoice"),
("big_bird", "FlaxBigBirdForMultipleChoice"),
("distilbert", "FlaxDistilBertForMultipleChoice"),
("electra", "FlaxElectraForMultipleChoice"),
("roberta", "FlaxRobertaForMultipleChoice"),
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"),
("roformer", "FlaxRoFormerForMultipleChoice"),
("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"),
]
)
UpperCAmelCase_ = OrderedDict(
[
("bert", "FlaxBertForNextSentencePrediction"),
]
)
UpperCAmelCase_ = OrderedDict(
[
("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"),
("whisper", "FlaxWhisperForConditionalGeneration"),
]
)
UpperCAmelCase_ = OrderedDict(
[
("whisper", "FlaxWhisperForAudioClassification"),
]
)
UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
)
UpperCAmelCase_ = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : List[str] = FLAX_MODEL_MAPPING
UpperCAmelCase_ = auto_class_update(FlaxAutoModel)
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Optional[Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING
UpperCAmelCase_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining")
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
UpperCAmelCase_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling")
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : List[str] = FLAX_MODEL_FOR_MASKED_LM_MAPPING
UpperCAmelCase_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling")
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Dict = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
UpperCAmelCase_ = auto_class_update(
FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base"
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : List[str] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
UpperCAmelCase_ = auto_class_update(
FlaxAutoModelForSequenceClassification, head_doc="sequence classification"
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Dict = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
UpperCAmelCase_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering")
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Union[str, Any] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
UpperCAmelCase_ = auto_class_update(
FlaxAutoModelForTokenClassification, head_doc="token classification"
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
UpperCAmelCase_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice")
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Any = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
UpperCAmelCase_ = auto_class_update(
FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction"
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
UpperCAmelCase_ = auto_class_update(
FlaxAutoModelForImageClassification, head_doc="image classification"
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : Optional[int] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
UpperCAmelCase_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling")
class __UpperCamelCase ( _BaseAutoModelClass ):
__A : str = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
UpperCAmelCase_ = auto_class_update(
FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling"
) | 32 |
from scipy.stats import spearmanr
import datasets
__A = '\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n'
__A = '\nArgs:\n predictions (`List[float]`): Predicted labels, as returned by a model.\n references (`List[float]`): Ground truth labels.\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n only the spearmanr score. Defaults to `False`.\nReturns:\n spearmanr (`float`): Spearman correlation coefficient.\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n Example 1:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n >>> print(results)\n {\'spearmanr\': -0.7}\n\n Example 2:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n ... predictions=[10, 9, 2.5, 6, 4],\n ... return_pvalue=True)\n >>> print(results[\'spearmanr\'])\n -0.7\n >>> print(round(results[\'spearmanr_pvalue\'], 2))\n 0.19\n'
__A = R'\\n@book{kokoska2000crc,\n title={CRC standard probability and statistics tables and formulae},\n author={Kokoska, Stephen and Zwillinger, Daniel},\n year={2000},\n publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\n journal = {Nature Methods},\n year = {2020},\n volume = {17},\n pages = {261--272},\n adsurl = {https://rdcu.be/b08Wh},\n doi = {10.1038/s41592-019-0686-2},\n}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class SCREAMING_SNAKE_CASE ( datasets.Metric ):
"""simple docstring"""
def __A ( self: Any ) -> Union[str, Any]:
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: str , __A: Optional[Any] , __A: Union[str, Any] , __A: Tuple=False ) -> List[Any]:
_A = spearmanr(__A , __A )
if return_pvalue:
return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
else:
return {"spearmanr": results[0]}
| 484 | 0 |
import pickle
import shutil
import tempfile
import unittest
from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
lowerCAmelCase__ = get_tests_dir('''fixtures/test_sentencepiece.model''')
@require_sentencepiece
@require_tokenizers
class snake_case__(_UpperCamelCase , unittest.TestCase ):
"""simple docstring"""
lowercase_ = XGLMTokenizer
lowercase_ = XGLMTokenizerFast
lowercase_ = True
lowercase_ = True
def snake_case ( self : List[str] ):
super().setUp()
# We have a SentencePiece fixture for testing
lowercase__ : Optional[int] = XGLMTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE )
tokenizer.save_pretrained(self.tmpdirname )
def snake_case ( self : Tuple ):
lowercase__ : Optional[Any] = "<pad>"
lowercase__ : Dict = 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 snake_case ( self : str ):
lowercase__ : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<s>" )
self.assertEqual(vocab_keys[1] , "<pad>" )
self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 1_008 )
def snake_case ( self : int ):
self.assertEqual(self.get_tokenizer().vocab_size , 1_008 )
def snake_case ( self : str ):
lowercase__ : int = XGLMTokenizer(SCREAMING_SNAKE_CASE , keep_accents=SCREAMING_SNAKE_CASE )
lowercase__ : List[Any] = 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 ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
lowercase__ : str = 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",
"é",
".",
] , )
lowercase__ : int = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE )
self.assertListEqual(
SCREAMING_SNAKE_CASE , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
] , )
lowercase__ : List[Any] = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE )
self.assertListEqual(
SCREAMING_SNAKE_CASE , [
SPIECE_UNDERLINE + "I",
SPIECE_UNDERLINE + "was",
SPIECE_UNDERLINE + "b",
"or",
"n",
SPIECE_UNDERLINE + "in",
SPIECE_UNDERLINE + "",
"<unk>",
"2",
"0",
"0",
"0",
",",
SPIECE_UNDERLINE + "and",
SPIECE_UNDERLINE + "this",
SPIECE_UNDERLINE + "is",
SPIECE_UNDERLINE + "f",
"al",
"s",
"<unk>",
".",
] , )
@cached_property
def snake_case ( self : Optional[Any] ):
return XGLMTokenizer.from_pretrained("facebook/xglm-564M" )
def snake_case ( self : Dict ):
with tempfile.NamedTemporaryFile() as f:
shutil.copyfile(SCREAMING_SNAKE_CASE , f.name )
lowercase__ : List[str] = XGLMTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE )
lowercase__ : Tuple = pickle.dumps(SCREAMING_SNAKE_CASE )
pickle.loads(SCREAMING_SNAKE_CASE )
def snake_case ( self : Optional[int] ):
if not self.test_rust_tokenizer:
return
lowercase__ : int = self.get_tokenizer()
lowercase__ : Optional[int] = self.get_rust_tokenizer()
lowercase__ : Optional[int] = "I was born in 92000, and this is falsé."
lowercase__ : List[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE )
lowercase__ : Tuple = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE )
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
lowercase__ : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE )
lowercase__ : Dict = rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE )
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
lowercase__ : Union[str, Any] = self.get_rust_tokenizer()
lowercase__ : List[str] = tokenizer.encode(SCREAMING_SNAKE_CASE )
lowercase__ : Tuple = rust_tokenizer.encode(SCREAMING_SNAKE_CASE )
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
@slow
def snake_case ( self : Optional[int] ):
lowercase__ : str = "Hello World!"
lowercase__ : List[str] = [2, 31_227, 4_447, 35]
self.assertListEqual(SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE ) )
@slow
def snake_case ( self : List[str] ):
lowercase__ : int = (
"This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will"
" add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth"
)
# fmt: off
lowercase__ : List[Any] = [2, 1_018, 67, 11, 1_988, 2_617, 5_631, 278, 11, 3_407, 48, 71_630, 28_085, 4, 3_234, 157, 13, 6, 5, 6, 4, 3_526, 768, 15, 659, 57, 298, 3_983, 864, 129, 21, 6, 5, 13_675, 377, 652, 7_580, 10_341, 155, 2_817, 422, 1_666, 7, 1_674, 53, 113, 202_277, 17_892, 33, 60, 87, 4, 3_234, 157, 61, 2_667, 52_376, 19, 88, 23, 735]
# fmt: on
self.assertListEqual(SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE ) )
@slow
def snake_case ( self : Optional[int] ):
# fmt: off
lowercase__ : Union[str, Any] = {
"input_ids": [[2, 108_825, 1_163, 15, 88_010, 473, 15_898, 157, 13_672, 1_857, 312, 8, 238_021, 1_163, 53, 13_672, 1_857, 312, 8, 53_283, 182_396, 8, 18_566, 16, 36_733, 4_101, 8, 230, 244_017, 122_553, 7, 15, 132_597, 4, 293, 12_511, 7_610, 4, 3_414, 132_597, 9, 4, 32_361, 362, 4, 734, 28_512, 32_569, 18, 4, 32_361, 26_096, 14_982, 73, 18_715, 21_433, 235_261, 15, 492, 12_427, 16, 53, 18_715, 21_433, 65_454, 15, 23_659, 563, 16, 278, 597, 2_843, 595, 7_931, 182_396, 64_186, 22, 886, 595, 132_981, 53, 25_540, 3_449, 43_982, 39_901, 5_951, 878, 330, 4, 27_694, 80_269, 312, 53, 6_517, 11_780, 611, 20_408, 5], [2, 6, 132_597, 67, 42_897, 33, 592, 8, 163_729, 25_540, 361, 136_997, 109_514, 173_230, 7, 501, 60, 102_913, 196, 5_631, 235, 63_243, 473, 6, 231_757, 74, 5_277, 7_905, 53, 3_095, 37_317, 22, 454, 183_874, 5], [2, 268, 31_298, 46_530, 6, 132_935, 43_831, 7, 597, 32, 24, 3_688, 9_865, 5]],
"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]]
} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=SCREAMING_SNAKE_CASE , model_name="facebook/xglm-564M" , padding=SCREAMING_SNAKE_CASE , )
| 720 |
from dataclasses import asdict, dataclass
from typing import Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase__ = logging.get_logger(__name__)
# TODO Update this
lowerCAmelCase__ = {
'''facebook/esm-1b''': '''https://huggingface.co/facebook/esm-1b/resolve/main/config.json''',
# See all ESM models at https://huggingface.co/models?filter=esm
}
class snake_case__(_UpperCamelCase ):
"""simple docstring"""
lowercase_ = """esm"""
def __init__( self : Any , SCREAMING_SNAKE_CASE : str=None , SCREAMING_SNAKE_CASE : Dict=None , SCREAMING_SNAKE_CASE : Dict=None , SCREAMING_SNAKE_CASE : Tuple=768 , SCREAMING_SNAKE_CASE : Any=12 , SCREAMING_SNAKE_CASE : Any=12 , SCREAMING_SNAKE_CASE : Optional[int]=3_072 , SCREAMING_SNAKE_CASE : Optional[int]=0.1 , SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE : Union[str, Any]=1_026 , SCREAMING_SNAKE_CASE : Tuple=0.02 , SCREAMING_SNAKE_CASE : str=1E-1_2 , SCREAMING_SNAKE_CASE : List[str]="absolute" , SCREAMING_SNAKE_CASE : Union[str, Any]=True , SCREAMING_SNAKE_CASE : Union[str, Any]=None , SCREAMING_SNAKE_CASE : Dict=False , SCREAMING_SNAKE_CASE : Optional[int]=False , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : Union[str, Any]=None , **SCREAMING_SNAKE_CASE : Union[str, Any] , ):
super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , mask_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
lowercase__ : List[str] = vocab_size
lowercase__ : int = hidden_size
lowercase__ : Union[str, Any] = num_hidden_layers
lowercase__ : List[str] = num_attention_heads
lowercase__ : List[str] = intermediate_size
lowercase__ : Union[str, Any] = hidden_dropout_prob
lowercase__ : List[str] = attention_probs_dropout_prob
lowercase__ : List[str] = max_position_embeddings
lowercase__ : List[str] = initializer_range
lowercase__ : Optional[Any] = layer_norm_eps
lowercase__ : Optional[int] = position_embedding_type
lowercase__ : Optional[int] = use_cache
lowercase__ : Optional[int] = emb_layer_norm_before
lowercase__ : List[str] = token_dropout
lowercase__ : Optional[int] = is_folding_model
if is_folding_model:
if esmfold_config is None:
logger.info("No esmfold_config supplied for folding model, using default values." )
lowercase__ : Dict = EsmFoldConfig()
elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
lowercase__ : Optional[int] = EsmFoldConfig(**SCREAMING_SNAKE_CASE )
lowercase__ : Dict = esmfold_config
if vocab_list is None:
logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!" )
lowercase__ : List[str] = get_default_vocab_list()
else:
lowercase__ : List[Any] = vocab_list
else:
lowercase__ : List[Any] = None
lowercase__ : List[str] = None
if self.esmfold_config is not None and getattr(self.esmfold_config , "use_esm_attn_map" , SCREAMING_SNAKE_CASE ):
raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!" )
def snake_case ( self : List[str] ):
lowercase__ : Optional[Any] = super().to_dict()
if isinstance(self.esmfold_config , SCREAMING_SNAKE_CASE ):
lowercase__ : Dict = self.esmfold_config.to_dict()
return output
@dataclass
class snake_case__:
"""simple docstring"""
lowercase_ = None
lowercase_ = True
lowercase_ = False
lowercase_ = False
lowercase_ = False
lowercase_ = 0
lowercase_ = True
lowercase_ = False
lowercase_ = 1_2_8
lowercase_ = None
def snake_case ( self : Optional[int] ):
if self.trunk is None:
lowercase__ : Dict = TrunkConfig()
elif isinstance(self.trunk , SCREAMING_SNAKE_CASE ):
lowercase__ : int = TrunkConfig(**self.trunk )
def snake_case ( self : Union[str, Any] ):
lowercase__ : int = asdict(self )
lowercase__ : Any = self.trunk.to_dict()
return output
@dataclass
class snake_case__:
"""simple docstring"""
lowercase_ = 4_8
lowercase_ = 1_0_2_4
lowercase_ = 1_2_8
lowercase_ = 3_2
lowercase_ = 3_2
lowercase_ = 3_2
lowercase_ = 0
lowercase_ = 0
lowercase_ = False
lowercase_ = 4
lowercase_ = 1_2_8
lowercase_ = None
def snake_case ( self : Dict ):
if self.structure_module is None:
lowercase__ : str = StructureModuleConfig()
elif isinstance(self.structure_module , SCREAMING_SNAKE_CASE ):
lowercase__ : Optional[int] = StructureModuleConfig(**self.structure_module )
if self.max_recycles <= 0:
raise ValueError(f"""`max_recycles` should be positive, got {self.max_recycles}.""" )
if self.sequence_state_dim % self.sequence_state_dim != 0:
raise ValueError(
"`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got"
f""" {self.sequence_state_dim} and {self.sequence_state_dim}.""" )
if self.pairwise_state_dim % self.pairwise_state_dim != 0:
raise ValueError(
"`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got"
f""" {self.pairwise_state_dim} and {self.pairwise_state_dim}.""" )
lowercase__ : Union[str, Any] = self.sequence_state_dim // self.sequence_head_width
lowercase__ : List[Any] = self.pairwise_state_dim // self.pairwise_head_width
if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
raise ValueError(
"`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got"
f""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.""" )
if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
raise ValueError(
"`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got"
f""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.""" )
if self.pairwise_state_dim % 2 != 0:
raise ValueError(f"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.""" )
if self.dropout >= 0.4:
raise ValueError(f"""`dropout` should not be greater than 0.4, got {self.dropout}.""" )
def snake_case ( self : Optional[Any] ):
lowercase__ : int = asdict(self )
lowercase__ : Optional[int] = self.structure_module.to_dict()
return output
@dataclass
class snake_case__:
"""simple docstring"""
lowercase_ = 3_8_4
lowercase_ = 1_2_8
lowercase_ = 1_6
lowercase_ = 1_2_8
lowercase_ = 1_2
lowercase_ = 4
lowercase_ = 8
lowercase_ = 0.1
lowercase_ = 8
lowercase_ = 1
lowercase_ = 2
lowercase_ = 7
lowercase_ = 1_0
lowercase_ = 1e-8
lowercase_ = 1e5
def snake_case ( self : Dict ):
return asdict(self )
def __lowerCamelCase ( ):
"""simple docstring"""
return (
"<cls>",
"<pad>",
"<eos>",
"<unk>",
"L",
"A",
"G",
"V",
"S",
"E",
"R",
"T",
"I",
"D",
"P",
"K",
"Q",
"N",
"F",
"Y",
"M",
"H",
"W",
"C",
"X",
"B",
"U",
"Z",
"O",
".",
"-",
"<null_1>",
"<mask>",
)
| 81 | 0 |
def __SCREAMING_SNAKE_CASE ( a__ : list ,a__ : list ,a__ : int ,a__ : int ,a__ : int ) -> int:
if index == number_of_items:
return 0
__A : Optional[int] = 0
__A : List[Any] = 0
__A : int = knapsack(a__ ,a__ ,a__ ,a__ ,index + 1 )
if weights[index] <= max_weight:
__A : Union[str, Any] = values[index] + knapsack(
a__ ,a__ ,a__ ,max_weight - weights[index] ,index + 1 )
return max(a__ ,a__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 17 | import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_tensorflow_text_available():
from transformers.models.bert import TFBertTokenizer
lowerCamelCase_ : Union[str, Any] = ["""bert-base-uncased""", """bert-base-cased"""]
lowerCamelCase_ : Tuple = """hf-internal-testing/tiny-bert-tf-only"""
if is_tf_available():
class a__ ( tf.keras.Model ):
def __init__( self , UpperCAmelCase ) -> Any:
super().__init__()
__a = tokenizer
__a = AutoConfig.from_pretrained(UpperCAmelCase )
__a = TFAutoModel.from_config(UpperCAmelCase )
def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase ) -> Optional[int]:
__a = self.tokenizer(UpperCAmelCase )
__a = self.bert(**UpperCAmelCase )
return out["pooler_output"]
@require_tf
@require_tensorflow_text
class a__ ( unittest.TestCase ):
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
super().setUp()
__a = [
BertTokenizer.from_pretrained(UpperCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
] # repeat for when fast_bert_tokenizer=false
__a = [TFBertTokenizer.from_pretrained(UpperCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
TFBertTokenizer.from_pretrained(UpperCAmelCase , use_fast_bert_tokenizer=UpperCAmelCase )
for checkpoint in TOKENIZER_CHECKPOINTS
]
assert len(self.tokenizers ) == len(self.tf_tokenizers )
__a = [
'This is a straightforward English test sentence.',
'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.',
'Now we\'re going to add some Chinese: 一 二 三 一二三',
'And some much more rare Chinese: 齉 堃 齉堃',
'Je vais aussi écrire en français pour tester les accents',
'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ',
]
__a = list(zip(self.test_sentences , self.test_sentences[::-1] ) )
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ):
for test_inputs in (self.test_sentences, self.paired_sentences):
__a = tokenizer(UpperCAmelCase , return_tensors='tf' , padding='longest' )
__a = tf_tokenizer(UpperCAmelCase )
for key in python_outputs.keys():
self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) )
self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
for tf_tokenizer in self.tf_tokenizers:
__a = tf_tokenizer(self.paired_sentences )
__a = tf_tokenizer(
text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , )
for key in merged_outputs.keys():
self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
for tf_tokenizer in self.tf_tokenizers:
__a = tf.function(UpperCAmelCase )
for test_inputs in (self.test_sentences, self.paired_sentences):
__a = tf.constant(UpperCAmelCase )
__a = compiled_tokenizer(UpperCAmelCase )
__a = tf_tokenizer(UpperCAmelCase )
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
for tf_tokenizer in self.tf_tokenizers:
__a = ModelToSave(tokenizer=UpperCAmelCase )
__a = tf.convert_to_tensor(self.test_sentences )
__a = model(UpperCAmelCase ) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
__a = Path(UpperCAmelCase ) / 'saved.model'
model.save(UpperCAmelCase )
__a = tf.keras.models.load_model(UpperCAmelCase )
__a = loaded_model(UpperCAmelCase )
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
| 559 | 0 |
"""simple docstring"""
import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch
import pyarrow as pa
import pytest
import requests
from packaging import version
from datasets import config
if config.PY_VERSION < version.parse('3.8'):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
def _lowerCamelCase ( lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Optional[int]=False ):
try:
lowercase__ : Tuple = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
lowercase__ : Dict = default
else:
# KEY is set, convert it to True or False.
try:
lowercase__ : Dict = strtobool(lowerCamelCase__ )
except ValueError:
# More values are supported, but let's keep the message simple.
raise ValueError(f'''If set, {key} must be yes or no.''' )
return _value
__snake_case = parse_flag_from_env('RUN_SLOW', default=False)
__snake_case = parse_flag_from_env('RUN_REMOTE', default=False)
__snake_case = parse_flag_from_env('RUN_LOCAL', default=True)
__snake_case = parse_flag_from_env('RUN_PACKAGED', default=True)
# Compression
__snake_case = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
__snake_case = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
__snake_case = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')
# Audio
__snake_case = pytest.mark.skipif(
# On Windows and OS X, soundfile installs sndfile
find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'),
reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ',
)
# Beam
__snake_case = pytest.mark.skipif(
not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'),
reason='test requires apache-beam and a compatible dill version',
)
# Dill-cloudpickle compatibility
__snake_case = pytest.mark.skipif(
config.DILL_VERSION <= version.parse('0.3.2'),
reason='test requires dill>0.3.2 for cloudpickle compatibility',
)
# Windows
__snake_case = pytest.mark.skipif(
sys.platform == 'win32',
reason='test should not be run on Windows',
)
def _lowerCamelCase ( lowerCamelCase__ : Dict ):
try:
import faiss # noqa
except ImportError:
lowercase__ : str = unittest.skip("""test requires faiss""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Optional[int] ):
try:
import regex # noqa
except ImportError:
lowercase__ : Dict = unittest.skip("""test requires regex""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Any ):
try:
import elasticsearch # noqa
except ImportError:
lowercase__ : Optional[Any] = unittest.skip("""test requires elasticsearch""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : str ):
try:
import sqlalchemy # noqa
except ImportError:
lowercase__ : Tuple = unittest.skip("""test requires sqlalchemy""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : List[Any] ):
if not config.TORCH_AVAILABLE:
lowercase__ : Union[str, Any] = unittest.skip("""test requires PyTorch""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : int ):
if not config.TF_AVAILABLE:
lowercase__ : str = unittest.skip("""test requires TensorFlow""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : List[Any] ):
if not config.JAX_AVAILABLE:
lowercase__ : Tuple = unittest.skip("""test requires JAX""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Union[str, Any] ):
if not config.PIL_AVAILABLE:
lowercase__ : List[Any] = unittest.skip("""test requires Pillow""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : List[str] ):
try:
import transformers # noqa F401
except ImportError:
return unittest.skip("""test requires transformers""" )(lowerCamelCase__ )
else:
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Dict ):
try:
import tiktoken # noqa F401
except ImportError:
return unittest.skip("""test requires tiktoken""" )(lowerCamelCase__ )
else:
return test_case
def _lowerCamelCase ( lowerCamelCase__ : List[Any] ):
try:
import spacy # noqa F401
except ImportError:
return unittest.skip("""test requires spacy""" )(lowerCamelCase__ )
else:
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Union[str, Any] ):
def _require_spacy_model(lowerCamelCase__ : List[str] ):
try:
import spacy # noqa F401
spacy.load(lowerCamelCase__ )
except ImportError:
return unittest.skip("""test requires spacy""" )(lowerCamelCase__ )
except OSError:
return unittest.skip("""test requires spacy model '{}'""".format(lowerCamelCase__ ) )(lowerCamelCase__ )
else:
return test_case
return _require_spacy_model
def _lowerCamelCase ( lowerCamelCase__ : Any ):
try:
import pyspark # noqa F401
except ImportError:
return unittest.skip("""test requires pyspark""" )(lowerCamelCase__ )
else:
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Any ):
try:
import joblibspark # noqa F401
except ImportError:
return unittest.skip("""test requires joblibspark""" )(lowerCamelCase__ )
else:
return test_case
def _lowerCamelCase ( lowerCamelCase__ : int ):
if not _run_slow_tests or _run_slow_tests == 0:
lowercase__ : List[Any] = unittest.skip("""test is slow""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Optional[Any] ):
if not _run_local_tests or _run_local_tests == 0:
lowercase__ : Tuple = unittest.skip("""test is local""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Optional[Any] ):
if not _run_packaged_tests or _run_packaged_tests == 0:
lowercase__ : Optional[Any] = unittest.skip("""test is packaged""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( lowerCamelCase__ : Union[str, Any] ):
if not _run_remote_tests or _run_remote_tests == 0:
lowercase__ : Dict = unittest.skip("""test requires remote""" )(lowerCamelCase__ )
return test_case
def _lowerCamelCase ( *lowerCamelCase__ : Dict ):
def decorate(cls : Optional[Any] ):
for name, fn in cls.__dict__.items():
if callable(lowerCamelCase__ ) and name.startswith("""test""" ):
for decorator in decorators:
lowercase__ : int = decorator(lowerCamelCase__ )
setattr(cls , lowerCamelCase__ , lowerCamelCase__ )
return cls
return decorate
class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ):
"""simple docstring"""
pass
class _SCREAMING_SNAKE_CASE ( __UpperCAmelCase ):
"""simple docstring"""
_a : str = 0
_a : Union[str, Any] = 1
_a : Any = 2
@contextmanager
def _lowerCamelCase ( lowerCamelCase__ : List[str]=OfflineSimulationMode.CONNECTION_FAILS , lowerCamelCase__ : Tuple=1E-16 ):
lowercase__ : Any = requests.Session().request
def timeout_request(lowerCamelCase__ : Dict , lowerCamelCase__ : str , lowerCamelCase__ : str , **lowerCamelCase__ : List[str] ):
# Change the url to an invalid url so that the connection hangs
lowercase__ : Optional[Any] = """https://10.255.255.1"""
if kwargs.get("""timeout""" ) is None:
raise RequestWouldHangIndefinitelyError(
f'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.''' )
lowercase__ : Any = timeout
try:
return online_request(lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ )
except Exception as e:
# The following changes in the error are just here to make the offline timeout error prettier
lowercase__ : Dict = url
lowercase__ : List[Any] = e.args[0]
lowercase__ : Union[str, Any] = (max_retry_error.args[0].replace("""10.255.255.1""" , f'''OfflineMock[{url}]''' ),)
lowercase__ : Optional[int] = (max_retry_error,)
raise
def raise_connection_error(lowerCamelCase__ : Dict , lowerCamelCase__ : Any , **lowerCamelCase__ : Tuple ):
raise requests.ConnectionError("""Offline mode is enabled.""" , request=lowerCamelCase__ )
if mode is OfflineSimulationMode.CONNECTION_FAILS:
with patch("""requests.Session.send""" , lowerCamelCase__ ):
yield
elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
# inspired from https://stackoverflow.com/a/904609
with patch("""requests.Session.request""" , lowerCamelCase__ ):
yield
elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
with patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCamelCase__ ):
yield
else:
raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" )
@contextmanager
def _lowerCamelCase ( *lowerCamelCase__ : Dict , **lowerCamelCase__ : Union[str, Any] ):
lowercase__ : Union[str, Any] = str(Path().resolve() )
with tempfile.TemporaryDirectory(*lowerCamelCase__ , **lowerCamelCase__ ) as tmp_dir:
try:
os.chdir(lowerCamelCase__ )
yield
finally:
os.chdir(lowerCamelCase__ )
@contextmanager
def _lowerCamelCase ( ):
import gc
gc.collect()
lowercase__ : List[str] = pa.total_allocated_bytes()
yield
assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def _lowerCamelCase ( ):
import gc
gc.collect()
lowercase__ : List[Any] = pa.total_allocated_bytes()
yield
assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def _lowerCamelCase ( lowerCamelCase__ : str , lowerCamelCase__ : Union[str, Any] ):
return deepcopy(lowerCamelCase__ ).integers(0 , 1_00 , 10 ).tolist() == deepcopy(lowerCamelCase__ ).integers(0 , 1_00 , 10 ).tolist()
def _lowerCamelCase ( lowerCamelCase__ : Union[str, Any] ):
import decorator
from requests.exceptions import HTTPError
def _wrapper(lowerCamelCase__ : Optional[int] , *lowerCamelCase__ : Any , **lowerCamelCase__ : int ):
try:
return func(*lowerCamelCase__ , **lowerCamelCase__ )
except HTTPError as err:
if str(lowerCamelCase__ ).startswith("""500""" ) or str(lowerCamelCase__ ).startswith("""502""" ):
pytest.xfail(str(lowerCamelCase__ ) )
raise err
return decorator.decorator(_wrapper , lowerCamelCase__ )
class _SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict:
lowercase__ : List[Any] = returncode
lowercase__ : Tuple = stdout
lowercase__ : Optional[int] = stderr
async def _lowerCamelCase ( lowerCamelCase__ : List[str] , lowerCamelCase__ : Optional[int] ):
while True:
lowercase__ : str = await stream.readline()
if line:
callback(lowerCamelCase__ )
else:
break
async def _lowerCamelCase ( lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Union[str, Any]=None , lowerCamelCase__ : List[Any]=None , lowerCamelCase__ : List[Any]=None , lowerCamelCase__ : Optional[int]=False , lowerCamelCase__ : str=False ):
if echo:
print("""\nRunning: """ , """ """.join(lowerCamelCase__ ) )
lowercase__ : List[Any] = await asyncio.create_subprocess_exec(
cmd[0] , *cmd[1:] , stdin=lowerCamelCase__ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCamelCase__ , )
# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
#
# If it starts hanging, will need to switch to the following code. The problem is that no data
# will be seen until it's done and if it hangs for example there will be no debug info.
# out, err = await p.communicate()
# return _RunOutput(p.returncode, out, err)
lowercase__ : Union[str, Any] = []
lowercase__ : Optional[Any] = []
def tee(lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : str="" ):
lowercase__ : int = line.decode("""utf-8""" ).rstrip()
sink.append(lowerCamelCase__ )
if not quiet:
print(lowerCamelCase__ , lowerCamelCase__ , file=lowerCamelCase__ )
# XXX: the timeout doesn't seem to make any difference here
await asyncio.wait(
[
_read_stream(p.stdout , lambda lowerCamelCase__ : tee(lowerCamelCase__ , lowerCamelCase__ , sys.stdout , label="""stdout:""" ) ),
_read_stream(p.stderr , lambda lowerCamelCase__ : tee(lowerCamelCase__ , lowerCamelCase__ , sys.stderr , label="""stderr:""" ) ),
] , timeout=lowerCamelCase__ , )
return _RunOutput(await p.wait() , lowerCamelCase__ , lowerCamelCase__ )
def _lowerCamelCase ( lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Optional[Any]=None , lowerCamelCase__ : Dict=None , lowerCamelCase__ : Any=1_80 , lowerCamelCase__ : Dict=False , lowerCamelCase__ : Union[str, Any]=True ):
lowercase__ : Tuple = asyncio.get_event_loop()
lowercase__ : Any = loop.run_until_complete(
_stream_subprocess(lowerCamelCase__ , env=lowerCamelCase__ , stdin=lowerCamelCase__ , timeout=lowerCamelCase__ , quiet=lowerCamelCase__ , echo=lowerCamelCase__ ) )
lowercase__ : Dict = """ """.join(lowerCamelCase__ )
if result.returncode > 0:
lowercase__ : List[str] = """\n""".join(result.stderr )
raise RuntimeError(
f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
f'''The combined stderr from workers follows:\n{stderr}''' )
# check that the subprocess actually did run and produced some output, should the test rely on
# the remote side to do the testing
if not result.stdout and not result.stderr:
raise RuntimeError(f'''\'{cmd_str}\' produced no output.''' )
return result
def _lowerCamelCase ( ):
lowercase__ : Optional[Any] = os.environ.get("""PYTEST_XDIST_WORKER""" , """gw0""" )
lowercase__ : Tuple = re.sub(r"""^gw""" , """""" , lowerCamelCase__ , 0 , re.M )
return int(lowerCamelCase__ )
def _lowerCamelCase ( ):
lowercase__ : Union[str, Any] = 2_95_00
lowercase__ : Optional[int] = pytest_xdist_worker_id()
return port + uniq_delta
| 708 |
"""simple docstring"""
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
UniSpeechConfig,
UniSpeechForCTC,
UniSpeechForPreTraining,
WavaVecaFeatureExtractor,
WavaVecaPhonemeCTCTokenizer,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
__snake_case = logging.get_logger(__name__)
__snake_case = {
'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',
'quantizer.weight_proj': 'quantizer.weight_proj',
'quantizer.vars': 'quantizer.codevectors',
'project_q': 'project_q',
'final_proj': 'project_hid',
'w2v_encoder.proj': 'ctc_proj',
'mask_emb': 'masked_spec_embed',
}
__snake_case = [
'ctc_proj',
'quantizer.weight_proj',
'quantizer.codevectors',
'project_q',
'project_hid',
]
def _lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : Tuple , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple ):
for attribute in key.split(""".""" ):
if is_finetuned:
if attribute in ["quantizer", "project_q", "project_hid"]:
# those layers are only relevant for pretraining and should be dropped
return
if attribute == "ctc_proj":
# we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
lowercase__ : List[Any] = """lm_head"""
lowercase__ : int = getattr(lowerCamelCase__ , lowerCamelCase__ )
if weight_type is not None:
lowercase__ : Any = getattr(lowerCamelCase__ , lowerCamelCase__ ).shape
else:
lowercase__ : Any = 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":
lowercase__ : Dict = value
elif weight_type == "weight_g":
lowercase__ : Union[str, Any] = value
elif weight_type == "weight_v":
lowercase__ : str = value
elif weight_type == "bias":
lowercase__ : int = value
else:
lowercase__ : Optional[Any] = value
logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' )
def _lowerCamelCase ( lowerCamelCase__ : Any , lowerCamelCase__ : str , lowerCamelCase__ : List[str] ):
lowercase__ : Tuple = []
lowercase__ : Dict = fairseq_model.state_dict()
lowercase__ : Optional[int] = hf_model.unispeech.feature_extractor
for name, value in fairseq_dict.items():
lowercase__ : str = False
if "conv_layers" in name:
load_conv_layer(
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , hf_model.config.feat_extract_norm == """group""" , )
lowercase__ : int = True
else:
for key, mapped_key in MAPPING.items():
lowercase__ : List[str] = """unispeech.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]:
lowercase__ : Dict = True
if "*" in mapped_key:
lowercase__ : List[str] = name.split(lowerCamelCase__ )[0].split(""".""" )[-2]
lowercase__ : Optional[Any] = mapped_key.replace("""*""" , lowerCamelCase__ )
if "weight_g" in name:
lowercase__ : Any = """weight_g"""
elif "weight_v" in name:
lowercase__ : Any = """weight_v"""
elif "bias" in name:
lowercase__ : List[str] = """bias"""
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
lowercase__ : str = """weight"""
else:
lowercase__ : str = None
set_recursively(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
continue
if not is_used:
unused_weights.append(lowerCamelCase__ )
logger.warning(f'''Unused weights: {unused_weights}''' )
def _lowerCamelCase ( lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str] ):
lowercase__ : Dict = full_name.split("""conv_layers.""" )[-1]
lowercase__ : Union[str, Any] = name.split(""".""" )
lowercase__ : List[Any] = int(items[0] )
lowercase__ : str = 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.'''
)
lowercase__ : Optional[int] = 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.'''
)
lowercase__ : int = 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."
)
lowercase__ : Tuple = 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.'''
)
lowercase__ : Any = 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__ : Optional[Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : List[str]=None , lowerCamelCase__ : List[Any]=None , lowerCamelCase__ : List[Any]=True ):
if config_path is not None:
lowercase__ : int = UniSpeechConfig.from_pretrained(lowerCamelCase__ )
else:
lowercase__ : Tuple = UniSpeechConfig()
if is_finetuned:
if dict_path:
lowercase__ : Any = Dictionary.load_from_json(lowerCamelCase__ )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
lowercase__ : int = target_dict.pad_index
lowercase__ : Tuple = target_dict.bos_index
lowercase__ : Dict = target_dict.eos_index
lowercase__ : Dict = len(target_dict.symbols )
lowercase__ : List[Any] = 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__ )
lowercase__ : Any = target_dict.indices
# fairseq has the <pad> and <s> switched
lowercase__ : Any = 42
lowercase__ : List[str] = 43
with open(lowerCamelCase__ , """w""" , encoding="""utf-8""" ) as vocab_handle:
json.dump(lowerCamelCase__ , lowerCamelCase__ )
lowercase__ : int = WavaVecaPhonemeCTCTokenizer(
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__ , )
lowercase__ : List[str] = True if config.feat_extract_norm == """layer""" else False
lowercase__ : List[Any] = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , )
lowercase__ : Any = WavaVecaProcessor(feature_extractor=lowerCamelCase__ , tokenizer=lowerCamelCase__ )
processor.save_pretrained(lowerCamelCase__ )
lowercase__ : Any = UniSpeechForCTC(lowerCamelCase__ )
else:
lowercase__ : Dict = UniSpeechForPreTraining(lowerCamelCase__ )
if is_finetuned:
lowercase__ , lowercase__ , lowercase__ : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} )
else:
lowercase__ , lowercase__ , lowercase__ : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] )
lowercase__ : str = model[0].eval()
recursively_load_weights(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
hf_unispeech.save_pretrained(lowerCamelCase__ )
if __name__ == "__main__":
__snake_case = 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'
)
__snake_case = parser.parse_args()
convert_unispeech_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
) | 128 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
_SCREAMING_SNAKE_CASE = {"configuration_reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConfig"]}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE = ["ReformerTokenizer"]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE = ["ReformerTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE = [
"REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"ReformerAttention",
"ReformerForMaskedLM",
"ReformerForQuestionAnswering",
"ReformerForSequenceClassification",
"ReformerLayer",
"ReformerModel",
"ReformerModelWithLMHead",
"ReformerPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_reformer import ReformerTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_reformer_fast import ReformerTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_reformer import (
REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
ReformerAttention,
ReformerForMaskedLM,
ReformerForQuestionAnswering,
ReformerForSequenceClassification,
ReformerLayer,
ReformerModel,
ReformerModelWithLMHead,
ReformerPreTrainedModel,
)
else:
import sys
_SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 181 |
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=True , lowerCamelCase__="pt" ) -> Dict:
__lowerCamelCase : Any = {'add_prefix_space': True} if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and not line.startswith(' ' ) else {}
__lowerCamelCase : int = padding_side
return tokenizer(
[line] , max_length=lowerCamelCase__ , padding='max_length' if pad_to_max_length else None , truncation=lowerCamelCase__ , return_tensors=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , **lowerCamelCase__ , )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , ) -> List[str]:
__lowerCamelCase : List[str] = input_ids.ne(lowerCamelCase__ ).any(dim=0 )
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class A_ ( SCREAMING_SNAKE_CASE ):
def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]="train" ,SCREAMING_SNAKE_CASE__ : Tuple=None ,SCREAMING_SNAKE_CASE__ : Dict=None ,SCREAMING_SNAKE_CASE__ : int=None ,SCREAMING_SNAKE_CASE__ : List[Any]="" ,):
super().__init__()
__lowerCamelCase : Optional[Any] = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.source')
__lowerCamelCase : Any = Path(SCREAMING_SNAKE_CASE__).joinpath(type_path + '.target')
__lowerCamelCase : List[Any] = self.get_char_lens(self.src_file)
__lowerCamelCase : List[Any] = max_source_length
__lowerCamelCase : List[str] = max_target_length
assert min(self.src_lens) > 0, F"found empty line in {self.src_file}"
__lowerCamelCase : Any = tokenizer
__lowerCamelCase : Optional[int] = prefix
if n_obs is not None:
__lowerCamelCase : Dict = self.src_lens[:n_obs]
__lowerCamelCase : str = src_lang
__lowerCamelCase : Any = tgt_lang
def __len__( self : Tuple):
return len(self.src_lens)
def __getitem__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str):
__lowerCamelCase : Dict = index + 1 # linecache starts at 1
__lowerCamelCase : Any = self.prefix + linecache.getline(str(self.src_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n')
__lowerCamelCase : int = linecache.getline(str(self.tgt_file) ,SCREAMING_SNAKE_CASE__).rstrip('\n')
assert source_line, F"empty source line for index {index}"
assert tgt_line, F"empty tgt line for index {index}"
# Need to add eos token manually for T5
if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
__lowerCamelCase : Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer
)
__lowerCamelCase : Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__) else self.tokenizer
__lowerCamelCase : List[str] = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_source_length ,'right')
__lowerCamelCase : Any = encode_line(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.max_target_length ,'right')
__lowerCamelCase : List[Any] = source_inputs['input_ids'].squeeze()
__lowerCamelCase : Tuple = target_inputs['input_ids'].squeeze()
__lowerCamelCase : Tuple = source_inputs['attention_mask'].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def lowerCAmelCase ( SCREAMING_SNAKE_CASE__ : int):
return [len(SCREAMING_SNAKE_CASE__) for x in Path(SCREAMING_SNAKE_CASE__).open().readlines()]
def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]):
__lowerCamelCase : Optional[Any] = torch.stack([x['input_ids'] for x in batch])
__lowerCamelCase : Any = torch.stack([x['attention_mask'] for x in batch])
__lowerCamelCase : Union[str, Any] = torch.stack([x['decoder_input_ids'] for x in batch])
__lowerCamelCase : Optional[int] = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__)
else self.tokenizer.pad_token_id
)
__lowerCamelCase : int = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer ,SCREAMING_SNAKE_CASE__)
else self.tokenizer.pad_token_id
)
__lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
__lowerCamelCase , __lowerCamelCase : int = trim_batch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)
__lowerCamelCase : Union[str, Any] = {
'input_ids': source_ids,
'attention_mask': source_mask,
'decoder_input_ids': y,
}
return batch
a =getLogger(__name__)
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any:
return list(itertools.chain.from_iterable(lowerCamelCase__ ) )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None:
__lowerCamelCase : str = get_git_info()
save_json(lowerCamelCase__ , os.path.join(lowerCamelCase__ , 'git_log.json' ) )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=4 , **lowerCamelCase__ ) -> List[str]:
with open(lowerCamelCase__ , 'w' ) as f:
json.dump(lowerCamelCase__ , lowerCamelCase__ , indent=lowerCamelCase__ , **lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple:
with open(lowerCamelCase__ ) as f:
return json.load(lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( ) -> List[str]:
__lowerCamelCase : str = git.Repo(search_parent_directories=lowerCamelCase__ )
__lowerCamelCase : Any = {
'repo_id': str(lowerCamelCase__ ),
'repo_sha': str(repo.head.object.hexsha ),
'repo_branch': str(repo.active_branch ),
'hostname': str(socket.gethostname() ),
}
return repo_infos
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List:
return list(map(lowerCamelCase__ , lowerCamelCase__ ) )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]:
with open(lowerCamelCase__ , 'wb' ) as f:
return pickle.dump(lowerCamelCase__ , lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str:
def remove_articles(lowerCamelCase__ ):
return re.sub(R'\b(a|an|the)\b' , ' ' , lowerCamelCase__ )
def white_space_fix(lowerCamelCase__ ):
return " ".join(text.split() )
def remove_punc(lowerCamelCase__ ):
__lowerCamelCase : Dict = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(lowerCamelCase__ ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__ ) ) ) )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int:
__lowerCamelCase : str = normalize_answer(lowerCamelCase__ ).split()
__lowerCamelCase : Optional[int] = normalize_answer(lowerCamelCase__ ).split()
__lowerCamelCase : Union[str, Any] = Counter(lowerCamelCase__ ) & Counter(lowerCamelCase__ )
__lowerCamelCase : Any = sum(common.values() )
if num_same == 0:
return 0
__lowerCamelCase : List[Any] = 1.0 * num_same / len(lowerCamelCase__ )
__lowerCamelCase : int = 1.0 * num_same / len(lowerCamelCase__ )
__lowerCamelCase : Optional[Any] = (2 * precision * recall) / (precision + recall)
return fa
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict:
return normalize_answer(lowerCamelCase__ ) == normalize_answer(lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict:
assert len(lowerCamelCase__ ) == len(lowerCamelCase__ )
__lowerCamelCase : Dict = 0
for hypo, pred in zip(lowerCamelCase__ , lowerCamelCase__ ):
em += exact_match_score(lowerCamelCase__ , lowerCamelCase__ )
if len(lowerCamelCase__ ) > 0:
em /= len(lowerCamelCase__ )
return {"em": em}
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple:
return model_prefix.startswith('rag' )
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]:
__lowerCamelCase : Optional[int] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
__lowerCamelCase : List[str] = 'dropout_rate'
for p in extra_params:
if getattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
if not hasattr(lowerCamelCase__ , lowerCamelCase__ ) and not hasattr(lowerCamelCase__ , equivalent_param[p] ):
logger.info('config doesn\'t have a `{}` attribute'.format(lowerCamelCase__ ) )
delattr(lowerCamelCase__ , lowerCamelCase__ )
continue
__lowerCamelCase : List[Any] = p if hasattr(lowerCamelCase__ , lowerCamelCase__ ) else equivalent_param[p]
setattr(lowerCamelCase__ , lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) )
delattr(lowerCamelCase__ , lowerCamelCase__ )
return hparams, config
| 652 | 0 |
import os
import sys
_UpperCAmelCase = os.path.join(os.path.dirname(__file__), 'src')
sys.path.append(SRC_DIR)
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoTokenizer,
add_start_docstrings,
)
_UpperCAmelCase = [
'torch',
'numpy',
'tokenizers',
'filelock',
'requests',
'tqdm',
'regex',
'sentencepiece',
'sacremoses',
'importlib_metadata',
'huggingface_hub',
]
@add_start_docstrings(AutoConfig.__doc__ )
def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE :Dict , **SCREAMING_SNAKE_CASE :str ) -> Tuple:
return AutoConfig.from_pretrained(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
@add_start_docstrings(AutoTokenizer.__doc__ )
def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE :Dict , **SCREAMING_SNAKE_CASE :Optional[Any] ) -> int:
return AutoTokenizer.from_pretrained(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
@add_start_docstrings(AutoModel.__doc__ )
def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE :List[Any] , **SCREAMING_SNAKE_CASE :Union[str, Any] ) -> List[Any]:
return AutoModel.from_pretrained(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
@add_start_docstrings(AutoModelForCausalLM.__doc__ )
def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE :Union[str, Any] , **SCREAMING_SNAKE_CASE :Optional[Any] ) -> List[str]:
return AutoModelForCausalLM.from_pretrained(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
@add_start_docstrings(AutoModelForMaskedLM.__doc__ )
def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE :Tuple , **SCREAMING_SNAKE_CASE :List[Any] ) -> Any:
return AutoModelForMaskedLM.from_pretrained(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
@add_start_docstrings(AutoModelForSequenceClassification.__doc__ )
def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE :Tuple , **SCREAMING_SNAKE_CASE :Optional[Any] ) -> List[Any]:
return AutoModelForSequenceClassification.from_pretrained(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
@add_start_docstrings(AutoModelForQuestionAnswering.__doc__ )
def _SCREAMING_SNAKE_CASE ( *SCREAMING_SNAKE_CASE :List[Any] , **SCREAMING_SNAKE_CASE :Optional[int] ) -> str:
return AutoModelForQuestionAnswering.from_pretrained(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) | 240 |
import argparse
import pytorch_lightning as pl
import torch
from torch import nn
from transformers import LongformerForQuestionAnswering, LongformerModel
class snake_case_ ( pl.LightningModule ):
def __init__( self : Union[str, Any] , _snake_case : List[str] )->List[str]:
'''simple docstring'''
super().__init__()
__lowerCAmelCase : Dict = model
__lowerCAmelCase : str = 2
__lowerCAmelCase : List[str] = nn.Linear(self.model.config.hidden_size , self.num_labels )
def UpperCAmelCase__ ( self : str )->Dict:
'''simple docstring'''
pass
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> str:
# load longformer model from model identifier
__lowerCAmelCase : int = LongformerModel.from_pretrained(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : Optional[int] = LightningModel(SCREAMING_SNAKE_CASE )
__lowerCAmelCase : str = torch.load(SCREAMING_SNAKE_CASE , map_location=torch.device("""cpu""" ) )
lightning_model.load_state_dict(ckpt["""state_dict"""] )
# init longformer question answering model
__lowerCAmelCase : Optional[Any] = LongformerForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE )
# transfer weights
longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() )
longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() )
longformer_for_qa.eval()
# save model
longformer_for_qa.save_pretrained(SCREAMING_SNAKE_CASE )
print(F'''Conversion successful. Model saved under {pytorch_dump_folder_path}''' )
if __name__ == "__main__":
_UpperCAmelCase = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--longformer_model',
default=None,
type=str,
required=True,
help='model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.',
)
parser.add_argument(
'--longformer_question_answering_ckpt_path',
default=None,
type=str,
required=True,
help='Path the official PyTorch Lightning Checkpoint.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
)
_UpperCAmelCase = parser.parse_args()
convert_longformer_qa_checkpoint_to_pytorch(
args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path
) | 240 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__a: Dict = logging.get_logger(__name__)
__a: Optional[Any] = {
'''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.json''',
# See all CANINE models at https://huggingface.co/models?filter=canine
}
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_lowerCamelCase = '''canine'''
def __init__( self : Any , lowerCamelCase : Tuple=768 , lowerCamelCase : Optional[Any]=12 , lowerCamelCase : Tuple=12 , lowerCamelCase : Any=3072 , lowerCamelCase : Optional[Any]="gelu" , lowerCamelCase : Any=0.1 , lowerCamelCase : int=0.1 , lowerCamelCase : List[Any]=1_6384 , lowerCamelCase : Any=16 , lowerCamelCase : int=0.02 , lowerCamelCase : List[Any]=1E-12 , lowerCamelCase : Dict=0 , lowerCamelCase : List[Any]=0XE000 , lowerCamelCase : List[str]=0XE001 , lowerCamelCase : List[Any]=4 , lowerCamelCase : Dict=4 , lowerCamelCase : Optional[Any]=8 , lowerCamelCase : Dict=1_6384 , lowerCamelCase : Optional[Any]=128 , **lowerCamelCase : Union[str, Any] , ) -> List[Any]:
"""simple docstring"""
super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase )
_UpperCAmelCase = max_position_embeddings
_UpperCAmelCase = hidden_size
_UpperCAmelCase = num_hidden_layers
_UpperCAmelCase = num_attention_heads
_UpperCAmelCase = intermediate_size
_UpperCAmelCase = hidden_act
_UpperCAmelCase = hidden_dropout_prob
_UpperCAmelCase = attention_probs_dropout_prob
_UpperCAmelCase = initializer_range
_UpperCAmelCase = type_vocab_size
_UpperCAmelCase = layer_norm_eps
# Character config:
_UpperCAmelCase = downsampling_rate
_UpperCAmelCase = upsampling_kernel_size
_UpperCAmelCase = num_hash_functions
_UpperCAmelCase = num_hash_buckets
_UpperCAmelCase = local_transformer_stride | 108 |
'''simple docstring'''
import json
import os
from datetime import date
from pathlib import Path
from tabulate import DataRow, TableFormat, tabulate
UpperCamelCase =TableFormat(
lineabove=None,
linebelowheader=None,
linebetweenrows=None,
linebelow=None,
headerrow=DataRow("", "|", "|"),
datarow=DataRow("", "|", "|"),
padding=1,
with_header_hide=None,
)
UpperCamelCase =[]
UpperCamelCase =[]
UpperCamelCase ={"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}}
UpperCamelCase =[
{
"type": "header",
"text": {
"type": "plain_text",
"text": f"🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results",
"emoji": True,
},
}
]
UpperCamelCase =0
for log in Path().glob("*.log"):
UpperCamelCase =0
with open(log, "r") as f:
for line in f:
UpperCamelCase =json.loads(line)
if line.get("nodeid", "") != "":
UpperCamelCase =line["nodeid"]
if line.get("duration", None) is not None:
UpperCamelCase =f"{line['duration']:.4f}"
if line.get("outcome", "") == "failed":
section_num_failed += 1
failed.append([test, duration, log.name.split("_")[0]])
total_num_failed += 1
group_info.append([str(log), section_num_failed, failed])
UpperCamelCase =[]
log.unlink()
UpperCamelCase =""
UpperCamelCase =[]
if total_num_failed > 0:
for name, num_failed, failed_tests in group_info:
if num_failed > 0:
if num_failed == 1:
message += f"*{name[1:]}: {num_failed} failed test*\n"
else:
message += f"*{name[1:]}: {num_failed} failed tests*\n"
UpperCamelCase =[]
UpperCamelCase ={}
for test in failed_tests:
UpperCamelCase =test[0].split("::")
UpperCamelCase =data[0].split("/")[-1]
if data[0] not in filesafailed:
UpperCamelCase =[data[1:]]
else:
filesafailed[data[0]] += [data[1:]]
failed_table.append(data)
UpperCamelCase =[test[0] for test in failed_table]
UpperCamelCase =list(set(files))
# Count number of instances in failed_tests
UpperCamelCase =[]
for file in individual_files:
table.append([file, len(filesafailed[file])])
UpperCamelCase =tabulate(
table,
headers=["Test Location", "Num Failed"],
tablefmt=hf_table_format,
stralign="right",
)
message += f"\n```\n{failed_table}\n```"
all_filesafailed.append(filesafailed)
if len(message) > 3000:
UpperCamelCase ="Too many failed tests, please see the full report in the Action results."
UpperCamelCase =len(err) + 10
UpperCamelCase =message[: 3000 - offset] + f"\n...\n```\n{err}"
print(f"### {message}")
else:
UpperCamelCase ="No failed tests! 🤗"
print(f"## {message}")
payload.append(no_error_payload)
if os.environ.get("TEST_TYPE", "") != "":
from slack_sdk import WebClient
UpperCamelCase =WebClient(token=os.environ["SLACK_API_TOKEN"])
if message != "No failed tests! 🤗":
UpperCamelCase ={
"type": "section",
"text": {
"type": "mrkdwn",
"text": message,
},
}
payload.append(md_report)
UpperCamelCase ={
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*For more details:*",
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Check Action results",
"emoji": True,
},
"url": f"https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}",
},
}
payload.append(action_button)
UpperCamelCase ={
"type": "context",
"elements": [
{
"type": "plain_text",
"text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}",
}
],
}
payload.append(date_report)
UpperCamelCase =client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload)
UpperCamelCase =response.data["ts"]
for failed_file in all_filesafailed:
for test_location, test_failures in failed_file.items():
# Keep only the first instance of the test name
UpperCamelCase =""
for i, row in enumerate(test_failures):
if row[0] != test_class:
UpperCamelCase =row[0]
else:
UpperCamelCase =""
UpperCamelCase ={
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```",
},
}
client.chat_postMessage(
channel="#accelerate-ci-daily",
thread_ts=ts,
blocks=[payload],
)
| 208 | 0 |
def _a ( UpperCAmelCase ) -> Optional[int]:
"""simple docstring"""
lowerCamelCase__ : Optional[Any] = len(UpperCAmelCase )
while cur > 1:
# Find the maximum number in arr
lowerCamelCase__ : int = arr.index(max(arr[0:cur] ) )
# Reverse from 0 to mi
lowerCamelCase__ : Optional[int] = arr[mi::-1] + arr[mi + 1 : len(UpperCAmelCase )]
# Reverse whole list
lowerCamelCase__ : int = arr[cur - 1 :: -1] + arr[cur : len(UpperCAmelCase )]
cur -= 1
return arr
if __name__ == "__main__":
_A : Optional[Any] = input('Enter numbers separated by a comma:\n').strip()
_A : List[Any] = [int(item) for item in user_input.split(',')]
print(pancake_sort(unsorted))
| 130 |
from ....configuration_utils import PretrainedConfig
from ....utils import logging
_A : List[str] = logging.get_logger(__name__)
# TODO: upload to AWS
_A : Tuple = {
'yjernite/retribert-base-uncased': (
'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json'
),
}
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
_UpperCAmelCase : str = "retribert"
def __init__( self : List[Any] , A : str=3_0_5_2_2 , A : int=7_6_8 , A : List[str]=8 , A : Union[str, Any]=1_2 , A : Optional[Any]=3_0_7_2 , A : Tuple="gelu" , A : Any=0.1 , A : Tuple=0.1 , A : Union[str, Any]=5_1_2 , A : str=2 , A : int=0.02 , A : Union[str, Any]=1e-12 , A : Any=True , A : Optional[int]=1_2_8 , A : Optional[int]=0 , **A : Optional[Any] , ) ->Dict:
super().__init__(pad_token_id=A , **A )
lowerCamelCase__ : List[Any] = vocab_size
lowerCamelCase__ : Optional[Any] = hidden_size
lowerCamelCase__ : int = num_hidden_layers
lowerCamelCase__ : Optional[Any] = num_attention_heads
lowerCamelCase__ : Optional[int] = hidden_act
lowerCamelCase__ : Optional[Any] = intermediate_size
lowerCamelCase__ : int = hidden_dropout_prob
lowerCamelCase__ : str = attention_probs_dropout_prob
lowerCamelCase__ : Dict = max_position_embeddings
lowerCamelCase__ : Tuple = type_vocab_size
lowerCamelCase__ : Optional[Any] = initializer_range
lowerCamelCase__ : int = layer_norm_eps
lowerCamelCase__ : List[str] = share_encoders
lowerCamelCase__ : Dict = projection_dim
| 130 | 1 |
'''simple docstring'''
def __snake_case (__UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ):
"""simple docstring"""
lowerCamelCase_ : List[Any] = set()
# Replace all the whitespace in our sentence
lowerCamelCase_ : Any = input_str.replace(''' ''' , '''''' )
for alpha in input_str:
if "a" <= alpha.lower() <= "z":
frequency.add(alpha.lower() )
return len(__UpperCAmelCase ) == 26
def __snake_case (__UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ):
"""simple docstring"""
lowerCamelCase_ : Dict = [False] * 26
for char in input_str:
if char.islower():
lowerCamelCase_ : List[Any] = True
elif char.isupper():
lowerCamelCase_ : List[Any] = True
return all(__UpperCAmelCase )
def __snake_case (__UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ):
"""simple docstring"""
return len({char for char in input_str.lower() if char.isalpha()} ) == 26
def __snake_case ():
"""simple docstring"""
from timeit import timeit
lowerCamelCase_ : List[str] = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest'''
print(timeit('''is_pangram()''' , setup=__UpperCAmelCase ) )
print(timeit('''is_pangram_faster()''' , setup=__UpperCAmelCase ) )
print(timeit('''is_pangram_fastest()''' , setup=__UpperCAmelCase ) )
# 5.348480500048026, 2.6477354579837993, 1.8470395830227062
# 5.036091582966037, 2.644472333951853, 1.8869528750656173
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 501 |
'''simple docstring'''
from dataclasses import dataclass
from typing import List, Optional, Union
import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel
from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
BaseOutput,
is_accelerate_available,
logging,
randn_tensor,
replace_example_docstring,
)
from .renderer import ShapERenderer
__lowerCamelCase : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name
__lowerCamelCase : Union[str, Any] = """
Examples:
```py
>>> from PIL import Image
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from diffusers.utils import export_to_gif, load_image
>>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")
>>> repo = \"openai/shap-e-img2img\"
>>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
>>> pipe = pipe.to(device)
>>> guidance_scale = 3.0
>>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
>>> image = load_image(image_url).convert(\"RGB\")
>>> images = pipe(
... image,
... guidance_scale=guidance_scale,
... num_inference_steps=64,
... frame_size=256,
... ).images
>>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
```
"""
@dataclass
class lowerCAmelCase__ ( _lowerCAmelCase ):
A = 42
class lowerCAmelCase__ ( _lowerCAmelCase ):
def __init__( self : Dict , UpperCamelCase_ : PriorTransformer , UpperCamelCase_ : CLIPVisionModel , UpperCamelCase_ : CLIPImageProcessor , UpperCamelCase_ : HeunDiscreteScheduler , UpperCamelCase_ : ShapERenderer , ) -> str:
"""simple docstring"""
super().__init__()
self.register_modules(
prior=UpperCamelCase_ , image_encoder=UpperCamelCase_ , image_processor=UpperCamelCase_ , scheduler=UpperCamelCase_ , renderer=UpperCamelCase_ , )
def __UpperCamelCase ( self : int , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : str , UpperCamelCase_ : List[str] , UpperCamelCase_ : int ) -> Dict:
"""simple docstring"""
if latents is None:
lowerCamelCase_ : str = randn_tensor(UpperCamelCase_ , generator=UpperCamelCase_ , device=UpperCamelCase_ , dtype=UpperCamelCase_ )
else:
if latents.shape != shape:
raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" )
lowerCamelCase_ : List[str] = latents.to(UpperCamelCase_ )
lowerCamelCase_ : int = latents * scheduler.init_noise_sigma
return latents
def __UpperCamelCase ( self : Optional[Any] , UpperCamelCase_ : List[str]=0 ) -> Optional[int]:
"""simple docstring"""
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError('''Please install accelerate via `pip install accelerate`''' )
lowerCamelCase_ : Tuple = torch.device(F"""cuda:{gpu_id}""" )
lowerCamelCase_ : Tuple = [self.image_encoder, self.prior]
for cpu_offloaded_model in models:
if cpu_offloaded_model is not None:
cpu_offload(UpperCamelCase_ , UpperCamelCase_ )
@property
def __UpperCamelCase ( self : List[Any] ) -> List[str]:
"""simple docstring"""
if self.device != torch.device('''meta''' ) or not hasattr(self.image_encoder , '''_hf_hook''' ):
return self.device
for module in self.image_encoder.modules():
if (
hasattr(UpperCamelCase_ , '''_hf_hook''' )
and hasattr(module._hf_hook , '''execution_device''' )
and module._hf_hook.execution_device is not None
):
return torch.device(module._hf_hook.execution_device )
return self.device
def __UpperCamelCase ( self : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : str , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] , ) -> int:
"""simple docstring"""
if isinstance(UpperCamelCase_ , UpperCamelCase_ ) and isinstance(image[0] , torch.Tensor ):
lowerCamelCase_ : Any = torch.cat(UpperCamelCase_ , axis=0 ) if image[0].ndim == 4 else torch.stack(UpperCamelCase_ , axis=0 )
if not isinstance(UpperCamelCase_ , torch.Tensor ):
lowerCamelCase_ : Any = self.image_processor(UpperCamelCase_ , return_tensors='''pt''' ).pixel_values[0].unsqueeze(0 )
lowerCamelCase_ : str = image.to(dtype=self.image_encoder.dtype , device=UpperCamelCase_ )
lowerCamelCase_ : Union[str, Any] = self.image_encoder(UpperCamelCase_ )['''last_hidden_state''']
lowerCamelCase_ : Dict = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256
lowerCamelCase_ : List[str] = image_embeds.repeat_interleave(UpperCamelCase_ , dim=0 )
if do_classifier_free_guidance:
lowerCamelCase_ : Dict = torch.zeros_like(UpperCamelCase_ )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
lowerCamelCase_ : Dict = torch.cat([negative_image_embeds, image_embeds] )
return image_embeds
@torch.no_grad()
@replace_example_docstring(UpperCamelCase_ )
def __call__( self : Union[str, Any] , UpperCamelCase_ : Union[PIL.Image.Image, List[PIL.Image.Image]] , UpperCamelCase_ : int = 1 , UpperCamelCase_ : int = 25 , UpperCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase_ : Optional[torch.FloatTensor] = None , UpperCamelCase_ : float = 4.0 , UpperCamelCase_ : int = 64 , UpperCamelCase_ : Optional[str] = "pil" , UpperCamelCase_ : bool = True , ) -> Optional[Any]:
"""simple docstring"""
if isinstance(UpperCamelCase_ , PIL.Image.Image ):
lowerCamelCase_ : List[Any] = 1
elif isinstance(UpperCamelCase_ , torch.Tensor ):
lowerCamelCase_ : Union[str, Any] = image.shape[0]
elif isinstance(UpperCamelCase_ , UpperCamelCase_ ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ):
lowerCamelCase_ : str = len(UpperCamelCase_ )
else:
raise ValueError(
F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(UpperCamelCase_ )}""" )
lowerCamelCase_ : List[Any] = self._execution_device
lowerCamelCase_ : Optional[Any] = batch_size * num_images_per_prompt
lowerCamelCase_ : Optional[int] = guidance_scale > 1.0
lowerCamelCase_ : Any = self._encode_image(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# prior
self.scheduler.set_timesteps(UpperCamelCase_ , device=UpperCamelCase_ )
lowerCamelCase_ : Dict = self.scheduler.timesteps
lowerCamelCase_ : List[Any] = self.prior.config.num_embeddings
lowerCamelCase_ : Optional[int] = self.prior.config.embedding_dim
lowerCamelCase_ : Dict = self.prepare_latents(
(batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , self.scheduler , )
# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
lowerCamelCase_ : Tuple = latents.reshape(latents.shape[0] , UpperCamelCase_ , UpperCamelCase_ )
for i, t in enumerate(self.progress_bar(UpperCamelCase_ ) ):
# expand the latents if we are doing classifier free guidance
lowerCamelCase_ : int = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
lowerCamelCase_ : List[Any] = self.scheduler.scale_model_input(UpperCamelCase_ , UpperCamelCase_ )
lowerCamelCase_ : Tuple = self.prior(
UpperCamelCase_ , timestep=UpperCamelCase_ , proj_embedding=UpperCamelCase_ , ).predicted_image_embedding
# remove the variance
lowerCamelCase_ , lowerCamelCase_ : List[Any] = noise_pred.split(
scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim
if do_classifier_free_guidance is not None:
lowerCamelCase_ , lowerCamelCase_ : Optional[int] = noise_pred.chunk(2 )
lowerCamelCase_ : Tuple = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
lowerCamelCase_ : str = self.scheduler.step(
UpperCamelCase_ , timestep=UpperCamelCase_ , sample=UpperCamelCase_ , ).prev_sample
if output_type == "latent":
return ShapEPipelineOutput(images=UpperCamelCase_ )
lowerCamelCase_ : Dict = []
for i, latent in enumerate(UpperCamelCase_ ):
print()
lowerCamelCase_ : Optional[int] = self.renderer.decode(
latent[None, :] , UpperCamelCase_ , size=UpperCamelCase_ , ray_batch_size=4_096 , n_coarse_samples=64 , n_fine_samples=128 , )
images.append(UpperCamelCase_ )
lowerCamelCase_ : Optional[Any] = torch.stack(UpperCamelCase_ )
if output_type not in ["np", "pil"]:
raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}""" )
lowerCamelCase_ : Union[str, Any] = images.cpu().numpy()
if output_type == "pil":
lowerCamelCase_ : str = [self.numpy_to_pil(UpperCamelCase_ ) for image in images]
# Offload last model to CPU
if hasattr(self , '''final_offload_hook''' ) and self.final_offload_hook is not None:
self.final_offload_hook.offload()
if not return_dict:
return (images,)
return ShapEPipelineOutput(images=UpperCamelCase_ )
| 501 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
lowerCAmelCase_ = {
'configuration_clipseg': [
'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP',
'CLIPSegConfig',
'CLIPSegTextConfig',
'CLIPSegVisionConfig',
],
'processing_clipseg': ['CLIPSegProcessor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ = [
'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST',
'CLIPSegModel',
'CLIPSegPreTrainedModel',
'CLIPSegTextModel',
'CLIPSegVisionModel',
'CLIPSegForImageSegmentation',
]
if TYPE_CHECKING:
from .configuration_clipseg import (
CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP,
CLIPSegConfig,
CLIPSegTextConfig,
CLIPSegVisionConfig,
)
from .processing_clipseg import CLIPSegProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_clipseg import (
CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST,
CLIPSegForImageSegmentation,
CLIPSegModel,
CLIPSegPreTrainedModel,
CLIPSegTextModel,
CLIPSegVisionModel,
)
else:
import sys
lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 708 |
"""simple docstring"""
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image
from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig
from transformers.utils import logging
logging.set_verbosity_info()
lowerCAmelCase_ = logging.get_logger(__name__)
def __UpperCAmelCase ( __lowerCamelCase ) -> Any:
lowercase__ : Any = SwinConfig(
embed_dim=1_92 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['''stage2''', '''stage3''', '''stage4'''] , )
lowercase__ : Optional[Any] = DetaConfig(
backbone_config=__lowerCamelCase , num_queries=9_00 , encoder_ffn_dim=20_48 , decoder_ffn_dim=20_48 , num_feature_levels=5 , assign_first_stage=__lowerCamelCase , with_box_refine=__lowerCamelCase , two_stage=__lowerCamelCase , )
# set labels
lowercase__ : Any = '''huggingface/label-files'''
if "o365" in model_name:
lowercase__ : Optional[Any] = 3_66
lowercase__ : List[Any] = '''object365-id2label.json'''
else:
lowercase__ : Union[str, Any] = 91
lowercase__ : Optional[int] = '''coco-detection-id2label.json'''
lowercase__ : List[Any] = num_labels
lowercase__ : str = json.load(open(cached_download(hf_hub_url(__lowerCamelCase , __lowerCamelCase , repo_type='''dataset''' ) ) , '''r''' ) )
lowercase__ : Union[str, Any] = {int(__lowerCamelCase ): v for k, v in idalabel.items()}
lowercase__ : Any = idalabel
lowercase__ : Any = {v: k for k, v in idalabel.items()}
return config
def __UpperCAmelCase ( __lowerCamelCase ) -> Any:
lowercase__ : Tuple = []
# stem
# fmt: off
rename_keys.append(('''backbone.0.body.patch_embed.proj.weight''', '''model.backbone.model.embeddings.patch_embeddings.projection.weight''') )
rename_keys.append(('''backbone.0.body.patch_embed.proj.bias''', '''model.backbone.model.embeddings.patch_embeddings.projection.bias''') )
rename_keys.append(('''backbone.0.body.patch_embed.norm.weight''', '''model.backbone.model.embeddings.norm.weight''') )
rename_keys.append(('''backbone.0.body.patch_embed.norm.bias''', '''model.backbone.model.embeddings.norm.bias''') )
# stages
for i in range(len(config.backbone_config.depths ) ):
for j in range(config.backbone_config.depths[i] ):
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm1.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm1.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm2.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.norm2.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias""", f"""model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias""") )
if i < 3:
rename_keys.append((f"""backbone.0.body.layers.{i}.downsample.reduction.weight""", f"""model.backbone.model.encoder.layers.{i}.downsample.reduction.weight""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.downsample.norm.weight""", f"""model.backbone.model.encoder.layers.{i}.downsample.norm.weight""") )
rename_keys.append((f"""backbone.0.body.layers.{i}.downsample.norm.bias""", f"""model.backbone.model.encoder.layers.{i}.downsample.norm.bias""") )
rename_keys.append(('''backbone.0.body.norm1.weight''', '''model.backbone.model.hidden_states_norms.stage2.weight''') )
rename_keys.append(('''backbone.0.body.norm1.bias''', '''model.backbone.model.hidden_states_norms.stage2.bias''') )
rename_keys.append(('''backbone.0.body.norm2.weight''', '''model.backbone.model.hidden_states_norms.stage3.weight''') )
rename_keys.append(('''backbone.0.body.norm2.bias''', '''model.backbone.model.hidden_states_norms.stage3.bias''') )
rename_keys.append(('''backbone.0.body.norm3.weight''', '''model.backbone.model.hidden_states_norms.stage4.weight''') )
rename_keys.append(('''backbone.0.body.norm3.bias''', '''model.backbone.model.hidden_states_norms.stage4.bias''') )
# transformer encoder
for i in range(config.encoder_layers ):
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight""", f"""model.encoder.layers.{i}.self_attn.sampling_offsets.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias""", f"""model.encoder.layers.{i}.self_attn.sampling_offsets.bias""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.attention_weights.weight""", f"""model.encoder.layers.{i}.self_attn.attention_weights.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.attention_weights.bias""", f"""model.encoder.layers.{i}.self_attn.attention_weights.bias""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.value_proj.weight""", f"""model.encoder.layers.{i}.self_attn.value_proj.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.value_proj.bias""", f"""model.encoder.layers.{i}.self_attn.value_proj.bias""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.output_proj.weight""", f"""model.encoder.layers.{i}.self_attn.output_proj.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.self_attn.output_proj.bias""", f"""model.encoder.layers.{i}.self_attn.output_proj.bias""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.weight""", f"""model.encoder.layers.{i}.self_attn_layer_norm.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.bias""", f"""model.encoder.layers.{i}.self_attn_layer_norm.bias""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""model.encoder.layers.{i}.fc1.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""model.encoder.layers.{i}.fc1.bias""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""model.encoder.layers.{i}.fc2.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""model.encoder.layers.{i}.fc2.bias""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.weight""", f"""model.encoder.layers.{i}.final_layer_norm.weight""") )
rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""model.encoder.layers.{i}.final_layer_norm.bias""") )
# transformer decoder
for i in range(config.decoder_layers ):
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight""", f"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias""", f"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.attention_weights.weight""", f"""model.decoder.layers.{i}.encoder_attn.attention_weights.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.attention_weights.bias""", f"""model.decoder.layers.{i}.encoder_attn.attention_weights.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.value_proj.weight""", f"""model.decoder.layers.{i}.encoder_attn.value_proj.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.value_proj.bias""", f"""model.decoder.layers.{i}.encoder_attn.value_proj.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.output_proj.weight""", f"""model.decoder.layers.{i}.encoder_attn.output_proj.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.cross_attn.output_proj.bias""", f"""model.decoder.layers.{i}.encoder_attn.output_proj.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.weight""", f"""model.decoder.layers.{i}.encoder_attn_layer_norm.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.bias""", f"""model.decoder.layers.{i}.encoder_attn_layer_norm.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""model.decoder.layers.{i}.self_attn.out_proj.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""model.decoder.layers.{i}.self_attn.out_proj.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.norm2.weight""", f"""model.decoder.layers.{i}.self_attn_layer_norm.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.norm2.bias""", f"""model.decoder.layers.{i}.self_attn_layer_norm.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""model.decoder.layers.{i}.fc1.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""model.decoder.layers.{i}.fc1.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""model.decoder.layers.{i}.fc2.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""model.decoder.layers.{i}.fc2.bias""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.weight""", f"""model.decoder.layers.{i}.final_layer_norm.weight""") )
rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""model.decoder.layers.{i}.final_layer_norm.bias""") )
# fmt: on
return rename_keys
def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[Any]:
lowercase__ : Dict = dct.pop(__lowerCamelCase )
lowercase__ : Optional[int] = val
def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> List[str]:
lowercase__ : Optional[int] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )]
for i in range(len(backbone_config.depths ) ):
lowercase__ : int = num_features[i]
for j in range(backbone_config.depths[i] ):
# fmt: off
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
lowercase__ : Optional[int] = state_dict.pop(f"""backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight""" )
lowercase__ : Optional[Any] = state_dict.pop(f"""backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
lowercase__ : List[Any] = in_proj_weight[:dim, :]
lowercase__ : List[str] = in_proj_bias[: dim]
lowercase__ : Dict = in_proj_weight[
dim : dim * 2, :
]
lowercase__ : str = in_proj_bias[
dim : dim * 2
]
lowercase__ : str = in_proj_weight[
-dim :, :
]
lowercase__ : List[str] = in_proj_bias[-dim :]
# fmt: on
def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]:
# transformer decoder self-attention layers
lowercase__ : List[str] = config.d_model
for i in range(config.decoder_layers ):
# read in weights + bias of input projection layer of self-attention
lowercase__ : Any = state_dict.pop(f"""transformer.decoder.layers.{i}.self_attn.in_proj_weight""" )
lowercase__ : Dict = state_dict.pop(f"""transformer.decoder.layers.{i}.self_attn.in_proj_bias""" )
# next, add query, keys and values (in that order) to the state dict
lowercase__ : Union[str, Any] = in_proj_weight[:hidden_size, :]
lowercase__ : str = in_proj_bias[:hidden_size]
lowercase__ : int = in_proj_weight[
hidden_size : hidden_size * 2, :
]
lowercase__ : List[Any] = in_proj_bias[hidden_size : hidden_size * 2]
lowercase__ : Union[str, Any] = in_proj_weight[-hidden_size:, :]
lowercase__ : Union[str, Any] = in_proj_bias[-hidden_size:]
def __UpperCAmelCase ( ) -> List[Any]:
lowercase__ : Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
lowercase__ : Optional[Any] = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw )
return im
@torch.no_grad()
def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Dict:
lowercase__ : Dict = get_deta_config(__lowerCamelCase )
# load original state dict
if model_name == "deta-swin-large":
lowercase__ : List[str] = hf_hub_download(repo_id='''nielsr/deta-checkpoints''' , filename='''adet_swin_ft.pth''' )
elif model_name == "deta-swin-large-o365":
lowercase__ : Dict = hf_hub_download(repo_id='''jozhang97/deta-swin-l-o365''' , filename='''deta_swin_pt_o365.pth''' )
else:
raise ValueError(f"""Model name {model_name} not supported""" )
lowercase__ : Optional[Any] = torch.load(__lowerCamelCase , map_location='''cpu''' )['''model''']
# original state dict
for name, param in state_dict.items():
print(__lowerCamelCase , param.shape )
# rename keys
lowercase__ : List[Any] = create_rename_keys(__lowerCamelCase )
for src, dest in rename_keys:
rename_key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
read_in_swin_q_k_v(__lowerCamelCase , config.backbone_config )
read_in_decoder_q_k_v(__lowerCamelCase , __lowerCamelCase )
# fix some prefixes
for key in state_dict.copy().keys():
if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
lowercase__ : str = state_dict.pop(__lowerCamelCase )
lowercase__ : Dict = val
if "input_proj" in key:
lowercase__ : Any = state_dict.pop(__lowerCamelCase )
lowercase__ : int = val
if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
lowercase__ : Tuple = state_dict.pop(__lowerCamelCase )
lowercase__ : int = val
# finally, create HuggingFace model and load state dict
lowercase__ : Any = DetaForObjectDetection(__lowerCamelCase )
model.load_state_dict(__lowerCamelCase )
model.eval()
lowercase__ : List[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu'''
model.to(__lowerCamelCase )
# load image processor
lowercase__ : Any = DetaImageProcessor(format='''coco_detection''' )
# verify our conversion on image
lowercase__ : Dict = prepare_img()
lowercase__ : Any = processor(images=__lowerCamelCase , return_tensors='''pt''' )
lowercase__ : str = encoding['''pixel_values''']
lowercase__ : Tuple = model(pixel_values.to(__lowerCamelCase ) )
# verify logits
print('''Logits:''' , outputs.logits[0, :3, :3] )
print('''Boxes:''' , outputs.pred_boxes[0, :3, :3] )
if model_name == "deta-swin-large":
lowercase__ : Any = torch.tensor(
[[-7.6_3_0_8, -2.8_4_8_5, -5.3_7_3_7], [-7.2_0_3_7, -4.5_5_0_5, -4.8_0_2_7], [-7.2_9_4_3, -4.2_6_1_1, -4.6_6_1_7]] )
lowercase__ : Any = torch.tensor([[0.4_9_8_7, 0.4_9_6_9, 0.9_9_9_9], [0.2_5_4_9, 0.5_4_9_8, 0.4_8_0_5], [0.5_4_9_8, 0.2_7_5_7, 0.0_5_6_9]] )
elif model_name == "deta-swin-large-o365":
lowercase__ : Dict = torch.tensor(
[[-8.0_1_2_2, -3.5_7_2_0, -4.9_7_1_7], [-8.1_5_4_7, -3.6_8_8_6, -4.6_3_8_9], [-7.6_6_1_0, -3.6_1_9_4, -5.0_1_3_4]] )
lowercase__ : int = torch.tensor([[0.2_5_2_3, 0.5_5_4_9, 0.4_8_8_1], [0.7_7_1_5, 0.4_1_4_9, 0.4_6_0_1], [0.5_5_0_3, 0.2_7_5_3, 0.0_5_7_5]] )
assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(__lowerCamelCase ) , atol=1E-4 )
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(__lowerCamelCase ) , atol=1E-4 )
print('''Everything ok!''' )
if pytorch_dump_folder_path:
# Save model and processor
logger.info(f"""Saving PyTorch model and processor to {pytorch_dump_folder_path}...""" )
Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase )
model.save_pretrained(__lowerCamelCase )
processor.save_pretrained(__lowerCamelCase )
# Push to hub
if push_to_hub:
print('''Pushing model and processor to hub...''' )
model.push_to_hub(f"""jozhang97/{model_name}""" )
processor.push_to_hub(f"""jozhang97/{model_name}""" )
if __name__ == "__main__":
lowerCAmelCase_ = argparse.ArgumentParser()
parser.add_argument(
'--model_name',
type=str,
default='deta-swin-large',
choices=['deta-swin-large', 'deta-swin-large-o365'],
help='Name of the model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default=None,
type=str,
help='Path to the folder to output PyTorch model.',
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
lowerCAmelCase_ = parser.parse_args()
convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 122 | 0 |
'''simple docstring'''
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
lowerCAmelCase_ : List[str] = logging.get_logger(__name__)
class lowerCamelCase_ ( __UpperCAmelCase ):
_lowerCAmelCase : str = ['input_features']
def __init__( self : List[str] , lowerCAmelCase__ : Union[str, Any]=80 , lowerCAmelCase__ : List[str]=1_60_00 , lowerCAmelCase__ : Any=1_60 , lowerCAmelCase__ : str=30 , lowerCAmelCase__ : Optional[Any]=4_00 , lowerCAmelCase__ : List[Any]=0.0 , lowerCAmelCase__ : int=False , **lowerCAmelCase__ : List[Any] , ):
"""simple docstring"""
super().__init__(
feature_size=lowerCAmelCase_ , sampling_rate=lowerCAmelCase_ , padding_value=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , **lowerCAmelCase_ , )
SCREAMING_SNAKE_CASE : Optional[Any] = n_fft
SCREAMING_SNAKE_CASE : List[Any] = hop_length
SCREAMING_SNAKE_CASE : Tuple = chunk_length
SCREAMING_SNAKE_CASE : List[Any] = chunk_length * sampling_rate
SCREAMING_SNAKE_CASE : Optional[int] = self.n_samples // hop_length
SCREAMING_SNAKE_CASE : Any = sampling_rate
SCREAMING_SNAKE_CASE : List[str] = mel_filter_bank(
num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowerCAmelCase_ , min_frequency=0.0 , max_frequency=80_00.0 , sampling_rate=lowerCAmelCase_ , norm='''slaney''' , mel_scale='''slaney''' , )
def __lowercase ( self : Tuple , lowerCAmelCase__ : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = spectrogram(
lowerCAmelCase_ , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel='''log10''' , )
SCREAMING_SNAKE_CASE : List[Any] = log_spec[:, :-1]
SCREAMING_SNAKE_CASE : List[str] = np.maximum(lowerCAmelCase_ , log_spec.max() - 8.0 )
SCREAMING_SNAKE_CASE : Any = (log_spec + 4.0) / 4.0
return log_spec
@staticmethod
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
def __lowercase ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[str] = 0.0 ):
"""simple docstring"""
if attention_mask is not None:
SCREAMING_SNAKE_CASE : int = np.array(lowerCAmelCase_ , np.intaa )
SCREAMING_SNAKE_CASE : int = []
for vector, length in zip(lowerCAmelCase_ , attention_mask.sum(-1 ) ):
SCREAMING_SNAKE_CASE : int = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 )
if length < normed_slice.shape[0]:
SCREAMING_SNAKE_CASE : Tuple = padding_value
normed_input_values.append(lowerCAmelCase_ )
else:
SCREAMING_SNAKE_CASE : List[Any] = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values]
return normed_input_values
def __call__( self : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict = True , lowerCAmelCase__ : Optional[Any] = None , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : List[str] = "max_length" , lowerCAmelCase__ : Union[str, Any] = None , lowerCAmelCase__ : Any = None , lowerCAmelCase__ : Any = None , **lowerCAmelCase__ : Union[str, Any] , ):
"""simple docstring"""
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"""
F""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"""
F""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" )
else:
logger.warning(
'''It is strongly recommended to pass the `sampling_rate` argument to this function. '''
'''Failing to do so can result in silent errors that might be hard to debug.''' )
SCREAMING_SNAKE_CASE : Tuple = isinstance(lowerCAmelCase_ , np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" )
SCREAMING_SNAKE_CASE : Tuple = is_batched_numpy or (
isinstance(lowerCAmelCase_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
SCREAMING_SNAKE_CASE : Optional[int] = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech]
elif not is_batched and not isinstance(lowerCAmelCase_ , np.ndarray ):
SCREAMING_SNAKE_CASE : str = np.asarray(lowerCAmelCase_ , dtype=np.floataa )
elif isinstance(lowerCAmelCase_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
SCREAMING_SNAKE_CASE : List[str] = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
SCREAMING_SNAKE_CASE : List[Any] = [np.asarray([raw_speech] ).T]
SCREAMING_SNAKE_CASE : Union[str, Any] = BatchFeature({'''input_features''': raw_speech} )
# convert into correct format for padding
SCREAMING_SNAKE_CASE : Union[str, Any] = self.pad(
lowerCAmelCase_ , padding=lowerCAmelCase_ , max_length=max_length if max_length else self.n_samples , truncation=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=return_attention_mask or do_normalize , )
# zero-mean and unit-variance normalization
if do_normalize:
SCREAMING_SNAKE_CASE : List[Any] = self.zero_mean_unit_var_norm(
padded_inputs['''input_features'''] , attention_mask=padded_inputs['''attention_mask'''] , padding_value=self.padding_value , )
SCREAMING_SNAKE_CASE : Tuple = np.stack(padded_inputs['''input_features'''] , axis=0 )
# make sure list is in array format
SCREAMING_SNAKE_CASE : Tuple = padded_inputs.get('''input_features''' ).transpose(2 , 0 , 1 )
SCREAMING_SNAKE_CASE : List[str] = [self._np_extract_fbank_features(lowerCAmelCase_ ) for waveform in input_features[0]]
if isinstance(input_features[0] , lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE : str = [np.asarray(lowerCAmelCase_ , dtype=np.floataa ) for feature in input_features]
else:
SCREAMING_SNAKE_CASE : Optional[int] = input_features
if return_attention_mask:
# rescale from sample (48000) to feature (3000)
SCREAMING_SNAKE_CASE : str = padded_inputs['attention_mask'][:, :: self.hop_length]
if return_tensors is not None:
SCREAMING_SNAKE_CASE : List[Any] = padded_inputs.convert_to_tensors(lowerCAmelCase_ )
return padded_inputs
def __lowercase ( self : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = copy.deepcopy(self.__dict__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
return output
| 527 |
"""simple docstring"""
import inspect
import unittest
from typing import List
import numpy as np
from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerModel,
)
from transformers.models.efficientformer.modeling_tf_efficientformer import (
TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_vision_available():
from PIL import Image
from transformers import EfficientFormerImageProcessor
class _lowerCAmelCase :
def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ = 1_3 , lowerCAmelCase_ = 6_4 , lowerCAmelCase_ = 2 , lowerCAmelCase_ = 3 , lowerCAmelCase_ = 3 , lowerCAmelCase_ = True , lowerCAmelCase_ = True , lowerCAmelCase_ = 1_2_8 , lowerCAmelCase_=[1_6, 3_2, 6_4, 1_2_8] , lowerCAmelCase_ = 7 , lowerCAmelCase_ = 4 , lowerCAmelCase_ = 3_7 , lowerCAmelCase_ = "gelu" , lowerCAmelCase_ = 0.1 , lowerCAmelCase_ = 0.1 , lowerCAmelCase_ = 1_0 , lowerCAmelCase_ = 0.02 , lowerCAmelCase_ = 2 , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 1_2_8 , lowerCAmelCase_ = [2, 2, 2, 2] , lowerCAmelCase_ = 2 , lowerCAmelCase_ = 2 , ) -> Dict:
_SCREAMING_SNAKE_CASE : Dict = parent
_SCREAMING_SNAKE_CASE : Optional[Any] = batch_size
_SCREAMING_SNAKE_CASE : List[Any] = image_size
_SCREAMING_SNAKE_CASE : int = patch_size
_SCREAMING_SNAKE_CASE : List[str] = num_channels
_SCREAMING_SNAKE_CASE : List[Any] = is_training
_SCREAMING_SNAKE_CASE : Union[str, Any] = use_labels
_SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size
_SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers
_SCREAMING_SNAKE_CASE : Dict = num_attention_heads
_SCREAMING_SNAKE_CASE : Any = intermediate_size
_SCREAMING_SNAKE_CASE : str = hidden_act
_SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob
_SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob
_SCREAMING_SNAKE_CASE : Union[str, Any] = type_sequence_label_size
_SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
_SCREAMING_SNAKE_CASE : int = encoder_stride
_SCREAMING_SNAKE_CASE : Tuple = num_attention_outputs
_SCREAMING_SNAKE_CASE : Any = embed_dim
_SCREAMING_SNAKE_CASE : str = embed_dim + 1
_SCREAMING_SNAKE_CASE : Union[str, Any] = resolution
_SCREAMING_SNAKE_CASE : int = depths
_SCREAMING_SNAKE_CASE : Optional[Any] = hidden_sizes
_SCREAMING_SNAKE_CASE : Optional[Any] = dim
_SCREAMING_SNAKE_CASE : Any = mlp_expansion_ratio
def A ( self ) -> List[str]:
_SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_SCREAMING_SNAKE_CASE : List[Any] = None
if self.use_labels:
_SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_SCREAMING_SNAKE_CASE : Tuple = self.get_config()
return config, pixel_values, labels
def A ( self ) -> List[str]:
return EfficientFormerConfig(
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=lowerCAmelCase_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , )
def A ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> str:
_SCREAMING_SNAKE_CASE : Optional[Any] = TFEfficientFormerModel(config=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Tuple = model(lowerCAmelCase_ , training=lowerCAmelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def A ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple:
_SCREAMING_SNAKE_CASE : Optional[Any] = self.type_sequence_label_size
_SCREAMING_SNAKE_CASE : Any = TFEfficientFormerForImageClassification(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[str] = model(lowerCAmelCase_ , labels=lowerCAmelCase_ , training=lowerCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
_SCREAMING_SNAKE_CASE : Tuple = 1
_SCREAMING_SNAKE_CASE : Any = TFEfficientFormerForImageClassification(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
_SCREAMING_SNAKE_CASE : List[str] = model(lowerCAmelCase_ , labels=lowerCAmelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def A ( self ) -> Dict:
_SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs()
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = config_and_inputs
_SCREAMING_SNAKE_CASE : Dict = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class _lowerCAmelCase ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
SCREAMING_SNAKE_CASE_: List[str] = (
(
TFEfficientFormerModel,
TFEfficientFormerForImageClassificationWithTeacher,
TFEfficientFormerForImageClassification,
)
if is_tf_available()
else ()
)
SCREAMING_SNAKE_CASE_: List[str] = (
{
'feature-extraction': TFEfficientFormerModel,
'image-classification': (
TFEfficientFormerForImageClassification,
TFEfficientFormerForImageClassificationWithTeacher,
),
}
if is_tf_available()
else {}
)
SCREAMING_SNAKE_CASE_: List[Any] = False
SCREAMING_SNAKE_CASE_: Optional[Any] = False
SCREAMING_SNAKE_CASE_: List[str] = False
SCREAMING_SNAKE_CASE_: Optional[Any] = False
SCREAMING_SNAKE_CASE_: str = False
def A ( self ) -> List[str]:
_SCREAMING_SNAKE_CASE : Union[str, Any] = TFEfficientFormerModelTester(self )
_SCREAMING_SNAKE_CASE : List[str] = ConfigTester(
self , config_class=lowerCAmelCase_ , has_text_modality=lowerCAmelCase_ , hidden_size=3_7 )
def A ( self ) -> Tuple:
self.config_tester.run_common_tests()
@unittest.skip(reason='EfficientFormer does not use inputs_embeds' )
def A ( self ) -> Dict:
pass
@unittest.skip(reason='EfficientFormer does not support input and output embeddings' )
def A ( self ) -> Optional[Any]:
pass
def A ( self ) -> Any:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_SCREAMING_SNAKE_CASE : List[Any] = model_class(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_SCREAMING_SNAKE_CASE : List[Any] = [*signature.parameters.keys()]
_SCREAMING_SNAKE_CASE : List[Any] = ['pixel_values']
self.assertListEqual(arg_names[:1] , lowerCAmelCase_ )
def A ( self ) -> Union[str, Any]:
def check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
_SCREAMING_SNAKE_CASE : List[str] = model_class(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) , training=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
_SCREAMING_SNAKE_CASE : Optional[Any] = getattr(
self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 )
self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ )
if hasattr(self.model_tester , 'encoder_seq_length' ):
_SCREAMING_SNAKE_CASE : List[str] = self.model_tester.encoder_seq_length
if hasattr(self.model_tester , 'chunk_length' ) and self.model_tester.chunk_length > 1:
_SCREAMING_SNAKE_CASE : Tuple = seq_length * self.model_tester.chunk_length
else:
_SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , )
if config.is_encoder_decoder:
_SCREAMING_SNAKE_CASE : List[str] = outputs.decoder_hidden_states
self.asseretIsInstance(lowerCAmelCase_ , (list, tuple) )
self.assertEqual(len(lowerCAmelCase_ ) , lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Dict = getattr(self.model_tester , 'seq_length' , lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Tuple = getattr(self.model_tester , 'decoder_seq_length' , lowerCAmelCase_ )
self.assertListEqual(
list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_SCREAMING_SNAKE_CASE : str = True
check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_SCREAMING_SNAKE_CASE : Any = True
check_hidden_states_output(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
def A ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False ) -> Any:
_SCREAMING_SNAKE_CASE : Tuple = super()._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ , return_labels=lowerCAmelCase_ )
if return_labels:
if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def A ( self ) -> str:
_SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCAmelCase_ )
@unittest.skip(reason='EfficientFormer does not implement masked image modeling yet' )
def A ( self ) -> Tuple:
_SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase_ )
def A ( self ) -> str:
_SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_ )
@slow
def A ( self ) -> List[str]:
for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_SCREAMING_SNAKE_CASE : str = TFEfficientFormerModel.from_pretrained(lowerCAmelCase_ )
self.assertIsNotNone(lowerCAmelCase_ )
def A ( self ) -> List[Any]:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
_SCREAMING_SNAKE_CASE : Optional[int] = True
_SCREAMING_SNAKE_CASE : Union[str, Any] = getattr(self.model_tester , 'seq_length' , lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : int = getattr(self.model_tester , 'encoder_seq_length' , lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[int] = getattr(self.model_tester , 'key_length' , lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : int = getattr(self.model_tester , 'chunk_length' , lowerCAmelCase_ )
if chunk_length is not None and hasattr(self.model_tester , 'num_hashes' ):
_SCREAMING_SNAKE_CASE : List[str] = encoder_seq_length * self.model_tester.num_hashes
for model_class in self.all_model_classes:
_SCREAMING_SNAKE_CASE : str = True
_SCREAMING_SNAKE_CASE : Tuple = False
_SCREAMING_SNAKE_CASE : Dict = True
_SCREAMING_SNAKE_CASE : List[Any] = model_class(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Union[str, Any] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) , training=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Any = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(lowerCAmelCase_ ) , self.model_tester.num_attention_outputs )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
_SCREAMING_SNAKE_CASE : List[str] = True
_SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[Any] = model(**self._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ ) , training=lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[int] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(lowerCAmelCase_ ) , self.model_tester.num_attention_outputs )
if chunk_length is not None:
self.assertListEqual(
list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , )
else:
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , )
def A ( self ) -> Any:
# We use a simplified version of this test for EfficientFormer because it requires training=False
# and Keras refuses to let us force that during functional construction
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# Prepare our model
_SCREAMING_SNAKE_CASE : int = model_class(lowerCAmelCase_ )
# These are maximally general inputs for the model, with multiple None dimensions
# Hopefully this will catch any conditionals that fail for flexible shapes
_SCREAMING_SNAKE_CASE : Optional[Any] = {
key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=lowerCAmelCase_ )
for key, val in model.input_signature.items()
if key in model.dummy_inputs
}
_SCREAMING_SNAKE_CASE : List[Any] = model(lowerCAmelCase_ )
self.assertTrue(outputs_dict is not None )
def lowercase__ ( ):
_SCREAMING_SNAKE_CASE : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
@require_vision
class _lowerCAmelCase ( unittest.TestCase ):
@cached_property
def A ( self ) -> str:
return (
EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300' )
if is_vision_available()
else None
)
@slow
def A ( self ) -> Dict:
_SCREAMING_SNAKE_CASE : Optional[int] = TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300' )
_SCREAMING_SNAKE_CASE : List[str] = self.default_image_processor
_SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_img()
_SCREAMING_SNAKE_CASE : int = image_processor(images=lowerCAmelCase_ , return_tensors='tf' )
# forward pass
_SCREAMING_SNAKE_CASE : Dict = model(**lowerCAmelCase_ , training=lowerCAmelCase_ )
# verify the logits
_SCREAMING_SNAKE_CASE : Optional[Any] = tf.TensorShape((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Optional[Any] = tf.constant([-0.0_555, 0.4_825, -0.0_852] )
self.assertTrue(np.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
@slow
def A ( self ) -> Optional[Any]:
_SCREAMING_SNAKE_CASE : List[Any] = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
'snap-research/efficientformer-l1-300' )
_SCREAMING_SNAKE_CASE : Optional[Any] = self.default_image_processor
_SCREAMING_SNAKE_CASE : List[str] = prepare_img()
_SCREAMING_SNAKE_CASE : List[Any] = image_processor(images=lowerCAmelCase_ , return_tensors='tf' )
# forward pass
_SCREAMING_SNAKE_CASE : List[Any] = model(**lowerCAmelCase_ , training=lowerCAmelCase_ )
# verify the logits
_SCREAMING_SNAKE_CASE : Union[str, Any] = tf.TensorShape((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , lowerCAmelCase_ )
_SCREAMING_SNAKE_CASE : Dict = tf.constant([-0.1_312, 0.4_353, -1.0_499] )
self.assertTrue(np.allclose(outputs.logits[0, :3] , lowerCAmelCase_ , atol=1e-4 ) )
| 621 | 0 |
"""simple docstring"""
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class __magic_name__ ( __a ):
'''simple docstring'''
@staticmethod
@abstractmethod
def _lowerCAmelCase ( _a ):
"""simple docstring"""
raise NotImplementedError()
@abstractmethod
def _lowerCAmelCase ( self ):
"""simple docstring"""
raise NotImplementedError()
| 706 |
"""simple docstring"""
from typing import List, Optional, TypeVar
from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal
lowerCAmelCase : List[Any] = logging.get_logger(__name__)
lowerCAmelCase : int = TypeVar("""DatasetType""", Dataset, IterableDataset)
def a__ ( snake_case__ , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = "first_exhausted" , ) -> DatasetType:
from .arrow_dataset import Dataset
from .iterable_dataset import IterableDataset
if not datasets:
raise ValueError("""Unable to interleave an empty list of datasets.""" )
for i, dataset in enumerate(snake_case__ ):
if not isinstance(snake_case__ , (Dataset, IterableDataset) ):
if isinstance(snake_case__ , (DatasetDict, IterableDatasetDict) ):
if not dataset:
raise ValueError(
F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
"""is an empty dataset dictionary.""" )
raise ValueError(
F'Dataset at position {i} has at least one split: {list(snake_case__ )}\n'
F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(snake_case__ ) )}\']' )
raise ValueError(
F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(snake_case__ ).__name__}.' )
if i == 0:
lowerCamelCase , lowerCamelCase = (
(Dataset, IterableDataset) if isinstance(snake_case__ , snake_case__ ) else (IterableDataset, Dataset)
)
elif not isinstance(snake_case__ , snake_case__ ):
raise ValueError(
F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' )
if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
raise ValueError(F'{stopping_strategy} is not supported. Please enter a valid stopping_strategy.' )
if dataset_type is Dataset:
return _interleave_map_style_datasets(
snake_case__ , snake_case__ , snake_case__ , info=snake_case__ , split=snake_case__ , stopping_strategy=snake_case__ )
else:
return _interleave_iterable_datasets(
snake_case__ , snake_case__ , snake_case__ , info=snake_case__ , split=snake_case__ , stopping_strategy=snake_case__ )
def a__ ( snake_case__ , snake_case__ = None , snake_case__ = None , snake_case__ = 0 , ) -> DatasetType:
if not dsets:
raise ValueError("""Unable to concatenate an empty list of datasets.""" )
for i, dataset in enumerate(snake_case__ ):
if not isinstance(snake_case__ , (Dataset, IterableDataset) ):
if isinstance(snake_case__ , (DatasetDict, IterableDatasetDict) ):
if not dataset:
raise ValueError(
F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} '
"""is an empty dataset dictionary.""" )
raise ValueError(
F'Dataset at position {i} has at least one split: {list(snake_case__ )}\n'
F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(snake_case__ ) )}\']' )
raise ValueError(
F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(snake_case__ ).__name__}.' )
if i == 0:
lowerCamelCase , lowerCamelCase = (
(Dataset, IterableDataset) if isinstance(snake_case__ , snake_case__ ) else (IterableDataset, Dataset)
)
elif not isinstance(snake_case__ , snake_case__ ):
raise ValueError(
F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' )
if dataset_type is Dataset:
return _concatenate_map_style_datasets(snake_case__ , info=snake_case__ , split=snake_case__ , axis=snake_case__ )
else:
return _concatenate_iterable_datasets(snake_case__ , info=snake_case__ , split=snake_case__ , axis=snake_case__ )
| 533 | 0 |
import random
import sys
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
lowerCamelCase : Tuple = '''Usage of script: script_name <size_of_canvas:int>'''
lowerCamelCase : List[Any] = [0] * 1_00 + [1] * 10
random.shuffle(choice)
def snake_case_ ( lowerCAmelCase_ : int ):
__lowercase : Dict = [[False for i in range(lowerCAmelCase_ )] for j in range(lowerCAmelCase_ )]
return canvas
def snake_case_ ( lowerCAmelCase_ : list[list[bool]] ):
for i, row in enumerate(lowerCAmelCase_ ):
for j, _ in enumerate(lowerCAmelCase_ ):
__lowercase : Dict = bool(random.getrandbits(1 ) )
def snake_case_ ( lowerCAmelCase_ : list[list[bool]] ):
__lowercase : Optional[int] = np.array(lowerCAmelCase_ )
__lowercase : List[str] = np.array(create_canvas(current_canvas.shape[0] ) )
for r, row in enumerate(lowerCAmelCase_ ):
for c, pt in enumerate(lowerCAmelCase_ ):
__lowercase : str = __judge_point(
lowerCAmelCase_ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] )
__lowercase : Dict = next_gen_canvas
del next_gen_canvas # cleaning memory as we move on.
__lowercase : list[list[bool]] = current_canvas.tolist()
return return_canvas
def snake_case_ ( lowerCAmelCase_ : bool , lowerCAmelCase_ : list[list[bool]] ):
__lowercase : Dict = 0
__lowercase : List[Any] = 0
# finding dead or alive neighbours count.
for i in neighbours:
for status in i:
if status:
alive += 1
else:
dead += 1
# handling duplicate entry for focus pt.
if pt:
alive -= 1
else:
dead -= 1
# running the rules of game here.
__lowercase : Dict = pt
if pt:
if alive < 2:
__lowercase : Tuple = False
elif alive == 2 or alive == 3:
__lowercase : Tuple = True
elif alive > 3:
__lowercase : Optional[int] = False
else:
if alive == 3:
__lowercase : Dict = True
return state
if __name__ == "__main__":
if len(sys.argv) != 2:
raise Exception(usage_doc)
lowerCamelCase : str = int(sys.argv[1])
# main working structure of this module.
lowerCamelCase : Optional[int] = create_canvas(canvas_size)
seed(c)
lowerCamelCase ,lowerCamelCase : Tuple = plt.subplots()
fig.show()
lowerCamelCase : Dict = ListedColormap(['''w''', '''k'''])
try:
while True:
lowerCamelCase : Optional[Any] = run(c)
ax.matshow(c, cmap=cmap)
fig.canvas.draw()
ax.cla()
except KeyboardInterrupt:
# do nothing.
pass | 149 |
from math import factorial
def snake_case_ ( lowerCAmelCase_ : int = 100 ):
return sum(map(lowerCAmelCase_ , str(factorial(lowerCAmelCase_ ) ) ) )
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 149 | 1 |
import gc
import unittest
from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
is_pipeline_test,
is_torch_available,
nested_simplify,
require_tf,
require_torch,
require_torch_gpu,
slow,
)
from .test_pipelines_common import ANY
@is_pipeline_test
class __A ( unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ = MODEL_FOR_MASKED_LM_MAPPING
UpperCAmelCase__ = TF_MODEL_FOR_MASKED_LM_MAPPING
def __snake_case ( self):
"""simple docstring"""
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
if is_torch_available():
import torch
torch.cuda.empty_cache()
@require_tf
def __snake_case ( self):
"""simple docstring"""
_lowerCamelCase : Dict = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , top_k=2 , framework='''tf''')
_lowerCamelCase : int = unmasker('''My name is <mask>''')
self.assertEqual(
nested_simplify(a__ , decimals=6) , [
{'''sequence''': '''My name is grouped''', '''score''': 2.1e-05, '''token''': 3_8015, '''token_str''': ''' grouped'''},
{'''sequence''': '''My name is accuser''', '''score''': 2.1e-05, '''token''': 2_5506, '''token_str''': ''' accuser'''},
] , )
_lowerCamelCase : List[str] = unmasker('''The largest city in France is <mask>''')
self.assertEqual(
nested_simplify(a__ , decimals=6) , [
{
'''sequence''': '''The largest city in France is grouped''',
'''score''': 2.1e-05,
'''token''': 3_8015,
'''token_str''': ''' grouped''',
},
{
'''sequence''': '''The largest city in France is accuser''',
'''score''': 2.1e-05,
'''token''': 2_5506,
'''token_str''': ''' accuser''',
},
] , )
_lowerCamelCase : str = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3)
self.assertEqual(
nested_simplify(a__ , decimals=6) , [
{'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 1_3606, '''token_str''': ''' Clara'''},
{'''sequence''': '''My name is Patrick''', '''score''': 2e-05, '''token''': 3499, '''token_str''': ''' Patrick'''},
{'''sequence''': '''My name is Te''', '''score''': 1.9e-05, '''token''': 2941, '''token_str''': ''' Te'''},
] , )
@require_torch
def __snake_case ( self):
"""simple docstring"""
_lowerCamelCase : Union[str, Any] = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , top_k=2 , framework='''pt''')
_lowerCamelCase : Optional[int] = unmasker('''My name is <mask>''')
self.assertEqual(
nested_simplify(a__ , decimals=6) , [
{'''sequence''': '''My name is Maul''', '''score''': 2.2e-05, '''token''': 3_5676, '''token_str''': ''' Maul'''},
{'''sequence''': '''My name isELS''', '''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS'''},
] , )
_lowerCamelCase : List[str] = unmasker('''The largest city in France is <mask>''')
self.assertEqual(
nested_simplify(a__ , decimals=6) , [
{
'''sequence''': '''The largest city in France is Maul''',
'''score''': 2.2e-05,
'''token''': 3_5676,
'''token_str''': ''' Maul''',
},
{'''sequence''': '''The largest city in France isELS''', '''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS'''},
] , )
_lowerCamelCase : Optional[Any] = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3)
self.assertEqual(
nested_simplify(a__ , decimals=6) , [
{'''sequence''': '''My name is Patrick''', '''score''': 2.1e-05, '''token''': 3499, '''token_str''': ''' Patrick'''},
{'''sequence''': '''My name is Te''', '''score''': 2e-05, '''token''': 2941, '''token_str''': ''' Te'''},
{'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 1_3606, '''token_str''': ''' Clara'''},
] , )
_lowerCamelCase : Union[str, Any] = unmasker('''My name is <mask> <mask>''' , top_k=2)
self.assertEqual(
nested_simplify(a__ , decimals=6) , [
[
{
'''score''': 2.2e-05,
'''token''': 3_5676,
'''token_str''': ''' Maul''',
'''sequence''': '''<s>My name is Maul<mask></s>''',
},
{'''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name isELS<mask></s>'''},
],
[
{
'''score''': 2.2e-05,
'''token''': 3_5676,
'''token_str''': ''' Maul''',
'''sequence''': '''<s>My name is<mask> Maul</s>''',
},
{'''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name is<mask>ELS</s>'''},
],
] , )
@require_torch_gpu
def __snake_case ( self):
"""simple docstring"""
_lowerCamelCase : int = pipeline('''fill-mask''' , model='''hf-internal-testing/tiny-random-distilbert''' , device=0 , framework='''pt''')
# convert model to fp16
pipe.model.half()
_lowerCamelCase : Tuple = pipe('''Paris is the [MASK] of France.''')
# We actually don't care about the result, we just want to make sure
# it works, meaning the float16 tensor got casted back to float32
# for postprocessing.
self.assertIsInstance(a__ , a__)
@slow
@require_torch
def __snake_case ( self):
"""simple docstring"""
_lowerCamelCase : Optional[int] = pipeline(task='''fill-mask''' , model='''distilroberta-base''' , top_k=2 , framework='''pt''')
self.run_large_test(a__)
@slow
@require_tf
def __snake_case ( self):
"""simple docstring"""
_lowerCamelCase : Optional[int] = pipeline(task='''fill-mask''' , model='''distilroberta-base''' , top_k=2 , framework='''tf''')
self.run_large_test(a__)
def __snake_case ( self , a__):
"""simple docstring"""
_lowerCamelCase : Any = unmasker('''My name is <mask>''')
self.assertEqual(
nested_simplify(a__) , [
{'''sequence''': '''My name is John''', '''score''': 0.008, '''token''': 610, '''token_str''': ''' John'''},
{'''sequence''': '''My name is Chris''', '''score''': 0.007, '''token''': 1573, '''token_str''': ''' Chris'''},
] , )
_lowerCamelCase : Union[str, Any] = unmasker('''The largest city in France is <mask>''')
self.assertEqual(
nested_simplify(a__) , [
{
'''sequence''': '''The largest city in France is Paris''',
'''score''': 0.251,
'''token''': 2201,
'''token_str''': ''' Paris''',
},
{
'''sequence''': '''The largest city in France is Lyon''',
'''score''': 0.214,
'''token''': 1_2790,
'''token_str''': ''' Lyon''',
},
] , )
_lowerCamelCase : List[Any] = unmasker('''My name is <mask>''' , targets=[''' Patrick''', ''' Clara''', ''' Teven'''] , top_k=3)
self.assertEqual(
nested_simplify(a__) , [
{'''sequence''': '''My name is Patrick''', '''score''': 0.005, '''token''': 3499, '''token_str''': ''' Patrick'''},
{'''sequence''': '''My name is Clara''', '''score''': 0.000, '''token''': 1_3606, '''token_str''': ''' Clara'''},
{'''sequence''': '''My name is Te''', '''score''': 0.000, '''token''': 2941, '''token_str''': ''' Te'''},
] , )
@require_torch
def __snake_case ( self):
"""simple docstring"""
_lowerCamelCase : int = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , framework='''pt''')
_lowerCamelCase : List[str] = None
_lowerCamelCase : Any = None
self.run_pipeline_test(a__ , [])
@require_tf
def __snake_case ( self):
"""simple docstring"""
_lowerCamelCase : Optional[int] = pipeline(task='''fill-mask''' , model='''sshleifer/tiny-distilroberta-base''' , framework='''tf''')
_lowerCamelCase : Optional[Any] = None
_lowerCamelCase : int = None
self.run_pipeline_test(a__ , [])
def __snake_case ( self , a__ , a__ , a__):
"""simple docstring"""
if tokenizer is None or tokenizer.mask_token_id is None:
self.skipTest('''The provided tokenizer has no mask token, (probably reformer or wav2vec2)''')
_lowerCamelCase : str = FillMaskPipeline(model=a__ , tokenizer=a__)
_lowerCamelCase : Optional[int] = [
F"""This is another {tokenizer.mask_token} test""",
]
return fill_masker, examples
def __snake_case ( self , a__ , a__):
"""simple docstring"""
_lowerCamelCase : List[Any] = fill_masker.tokenizer
_lowerCamelCase : List[str] = fill_masker.model
_lowerCamelCase : Union[str, Any] = fill_masker(
F"""This is a {tokenizer.mask_token}""" , )
self.assertEqual(
a__ , [
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
] , )
_lowerCamelCase : Optional[int] = fill_masker([F"""This is a {tokenizer.mask_token}"""])
self.assertEqual(
a__ , [
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
] , )
_lowerCamelCase : Any = fill_masker([F"""This is a {tokenizer.mask_token}""", F"""Another {tokenizer.mask_token} great test."""])
self.assertEqual(
a__ , [
[
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
],
[
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
],
] , )
with self.assertRaises(a__):
fill_masker([None])
# No mask_token is not supported
with self.assertRaises(a__):
fill_masker('''This is''')
self.run_test_top_k(a__ , a__)
self.run_test_targets(a__ , a__)
self.run_test_top_k_targets(a__ , a__)
self.fill_mask_with_duplicate_targets_and_top_k(a__ , a__)
self.fill_mask_with_multiple_masks(a__ , a__)
def __snake_case ( self , a__ , a__):
"""simple docstring"""
_lowerCamelCase : str = tokenizer.get_vocab()
_lowerCamelCase : Optional[int] = sorted(vocab.keys())[:2]
# Pipeline argument
_lowerCamelCase : List[str] = FillMaskPipeline(model=a__ , tokenizer=a__ , targets=a__)
_lowerCamelCase : Any = fill_masker(F"""This is a {tokenizer.mask_token}""")
self.assertEqual(
a__ , [
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
] , )
_lowerCamelCase : Optional[int] = {vocab[el] for el in targets}
self.assertEqual({el['''token'''] for el in outputs} , a__)
_lowerCamelCase : Dict = [tokenizer.decode([x]) for x in target_ids]
self.assertEqual({el['''token_str'''] for el in outputs} , set(a__))
# Call argument
_lowerCamelCase : Optional[int] = FillMaskPipeline(model=a__ , tokenizer=a__)
_lowerCamelCase : int = fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=a__)
self.assertEqual(
a__ , [
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
] , )
_lowerCamelCase : List[Any] = {vocab[el] for el in targets}
self.assertEqual({el['''token'''] for el in outputs} , a__)
_lowerCamelCase : Dict = [tokenizer.decode([x]) for x in target_ids]
self.assertEqual({el['''token_str'''] for el in outputs} , set(a__))
# Score equivalence
_lowerCamelCase : Optional[int] = fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=a__)
_lowerCamelCase : Dict = [top_mask['''token_str'''] for top_mask in outputs]
_lowerCamelCase : str = [top_mask['''score'''] for top_mask in outputs]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(a__) == set(a__):
_lowerCamelCase : List[Any] = fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=a__)
_lowerCamelCase : List[Any] = [top_mask['''score'''] for top_mask in unmasked_targets]
self.assertEqual(nested_simplify(a__) , nested_simplify(a__))
# Raises with invalid
with self.assertRaises(a__):
_lowerCamelCase : Any = fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=[])
# For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
if "" not in tokenizer.get_vocab():
with self.assertRaises(a__):
_lowerCamelCase : str = fill_masker(F"""This is a {tokenizer.mask_token}""" , targets=[''''''])
with self.assertRaises(a__):
_lowerCamelCase : Union[str, Any] = fill_masker(F"""This is a {tokenizer.mask_token}""" , targets='''''')
def __snake_case ( self , a__ , a__):
"""simple docstring"""
_lowerCamelCase : Any = FillMaskPipeline(model=a__ , tokenizer=a__ , top_k=2)
_lowerCamelCase : Union[str, Any] = fill_masker(F"""This is a {tokenizer.mask_token}""")
self.assertEqual(
a__ , [
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
] , )
_lowerCamelCase : Tuple = FillMaskPipeline(model=a__ , tokenizer=a__)
_lowerCamelCase : List[Any] = fill_masker(F"""This is a {tokenizer.mask_token}""" , top_k=2)
self.assertEqual(
a__ , [
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
] , )
self.assertEqual(nested_simplify(a__) , nested_simplify(a__))
def __snake_case ( self , a__ , a__):
"""simple docstring"""
_lowerCamelCase : Dict = tokenizer.get_vocab()
_lowerCamelCase : Any = FillMaskPipeline(model=a__ , tokenizer=a__)
# top_k=2, ntargets=3
_lowerCamelCase : List[Any] = sorted(vocab.keys())[:3]
_lowerCamelCase : Tuple = fill_masker(F"""This is a {tokenizer.mask_token}""" , top_k=2 , targets=a__)
# If we use the most probably targets, and filter differently, we should still
# have the same results
_lowerCamelCase : Union[str, Any] = [el['''token_str'''] for el in sorted(a__ , key=lambda a__: x["score"] , reverse=a__)]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(a__).issubset(a__):
_lowerCamelCase : Tuple = fill_masker(F"""This is a {tokenizer.mask_token}""" , top_k=3 , targets=a__)
# They should yield exactly the same result
self.assertEqual(nested_simplify(a__) , nested_simplify(a__))
def __snake_case ( self , a__ , a__):
"""simple docstring"""
_lowerCamelCase : str = FillMaskPipeline(model=a__ , tokenizer=a__)
_lowerCamelCase : Any = tokenizer.get_vocab()
# String duplicates + id duplicates
_lowerCamelCase : Any = sorted(vocab.keys())[:3]
_lowerCamelCase : str = [targets[0], targets[1], targets[0], targets[2], targets[1]]
_lowerCamelCase : str = fill_masker(F"""My name is {tokenizer.mask_token}""" , targets=a__ , top_k=10)
# The target list contains duplicates, so we can't output more
# than them
self.assertEqual(len(a__) , 3)
def __snake_case ( self , a__ , a__):
"""simple docstring"""
_lowerCamelCase : Tuple = FillMaskPipeline(model=a__ , tokenizer=a__)
_lowerCamelCase : Union[str, Any] = fill_masker(
F"""This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}""" , top_k=2)
self.assertEqual(
a__ , [
[
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
],
[
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
],
[
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
{'''sequence''': ANY(a__), '''score''': ANY(a__), '''token''': ANY(a__), '''token_str''': ANY(a__)},
],
] , )
| 613 |
def __UpperCAmelCase( lowercase_ ):
# if the collection is empty, returns empty
if collection == []:
return []
# get some information about the collection
_lowerCamelCase : Tuple = len(lowercase_ )
_lowerCamelCase : List[str] = max(lowercase_ )
_lowerCamelCase : Any = min(lowercase_ )
# create the counting array
_lowerCamelCase : str = coll_max + 1 - coll_min
_lowerCamelCase : Union[str, Any] = [0] * counting_arr_length
# count how much a number appears in the collection
for number in collection:
counting_arr[number - coll_min] += 1
# sum each position with it's predecessors. now, counting_arr[i] tells
# us how many elements <= i has in the collection
for i in range(1 , lowercase_ ):
_lowerCamelCase : Union[str, Any] = counting_arr[i] + counting_arr[i - 1]
# create the output collection
_lowerCamelCase : Dict = [0] * coll_len
# place the elements in the output, respecting the original order (stable
# sort) from end to begin, updating counting_arr
for i in reversed(range(0 , lowercase_ ) ):
_lowerCamelCase : Union[str, Any] = collection[i]
counting_arr[collection[i] - coll_min] -= 1
return ordered
def __UpperCAmelCase( lowercase_ ):
return "".join([chr(lowercase_ ) for i in counting_sort([ord(lowercase_ ) for c in string] )] )
if __name__ == "__main__":
# Test string sort
assert counting_sort_string('thisisthestring') == "eghhiiinrsssttt"
_lowerCamelCase = input('Enter numbers separated by a comma:\n').strip()
_lowerCamelCase = [int(item) for item in user_input.split(',')]
print(counting_sort(unsorted))
| 613 | 1 |
import re
from filelock import FileLock
try:
import nltk
__lowercase : str =True
except (ImportError, ModuleNotFoundError):
__lowercase : Optional[Any] =False
if NLTK_AVAILABLE:
with FileLock(""".lock""") as lock:
nltk.download("""punkt""", quiet=True)
def a__ ( lowercase__ ):
'''simple docstring'''
re.sub("<n>" , "" , lowercase__ ) # remove pegasus newline char
assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)"
return "\n".join(nltk.sent_tokenize(lowercase__ ) )
| 54 |
import sys
def a__ ( lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =len(lowercase__ )
UpperCAmelCase_ =[[0 for x in range(lowercase__ )] for x in range(lowercase__ )]
UpperCAmelCase_ =[[0 for x in range(lowercase__ )] for x in range(lowercase__ )]
for chain_length in range(2 , lowercase__ ):
for a in range(1 , n - chain_length + 1 ):
UpperCAmelCase_ =a + chain_length - 1
UpperCAmelCase_ =sys.maxsize
for c in range(lowercase__ , lowercase__ ):
UpperCAmelCase_ =(
matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
)
if cost < matrix[a][b]:
UpperCAmelCase_ =cost
UpperCAmelCase_ =c
return matrix, sol
def a__ ( lowercase__ , lowercase__ , lowercase__ ):
'''simple docstring'''
if i == j:
print("A" + str(lowercase__ ) , end=" " )
else:
print("(" , end=" " )
print_optiomal_solution(lowercase__ , lowercase__ , optimal_solution[i][j] )
print_optiomal_solution(lowercase__ , optimal_solution[i][j] + 1 , lowercase__ )
print(")" , end=" " )
def a__ ( ):
'''simple docstring'''
UpperCAmelCase_ =[3_0, 3_5, 1_5, 5, 1_0, 2_0, 2_5]
UpperCAmelCase_ =len(lowercase__ )
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
UpperCAmelCase_ , UpperCAmelCase_ =matrix_chain_order(lowercase__ )
print("No. of Operation required: " + str(matrix[1][n - 1] ) )
print_optiomal_solution(lowercase__ , 1 , n - 1 )
if __name__ == "__main__":
main()
| 54 | 1 |
"""simple docstring"""
import argparse
import json
from pathlib import Path
import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging
logging.set_verbosity_info()
_lowerCamelCase : Optional[int] = logging.get_logger(__name__)
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ : Optional[Any] = ASTConfig()
if "10-10" in model_name:
pass
elif "speech-commands" in model_name:
A_ : List[Any] = 128
elif "12-12" in model_name:
A_ : Tuple = 12
A_ : Optional[Any] = 12
elif "14-14" in model_name:
A_ : Union[str, Any] = 14
A_ : Optional[Any] = 14
elif "16-16" in model_name:
A_ : int = 16
A_ : List[Any] = 16
else:
raise ValueError('''Model not supported''' )
A_ : List[Any] = '''huggingface/label-files'''
if "speech-commands" in model_name:
A_ : List[str] = 35
A_ : int = '''speech-commands-v2-id2label.json'''
else:
A_ : List[str] = 527
A_ : Optional[Any] = '''audioset-id2label.json'''
A_ : List[str] = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase , repo_type='''dataset''' ) , '''r''' ) )
A_ : List[Any] = {int(_UpperCAmelCase ): v for k, v in idalabel.items()}
A_ : Union[str, Any] = idalabel
A_ : Optional[int] = {v: k for k, v in idalabel.items()}
return config
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
if "module.v" in name:
A_ : str = name.replace('''module.v''' , '''audio_spectrogram_transformer''' )
if "cls_token" in name:
A_ : Optional[int] = name.replace('''cls_token''' , '''embeddings.cls_token''' )
if "dist_token" in name:
A_ : Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' )
if "pos_embed" in name:
A_ : Union[str, Any] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' )
if "patch_embed.proj" in name:
A_ : Optional[int] = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
# transformer blocks
if "blocks" in name:
A_ : List[str] = name.replace('''blocks''' , '''encoder.layer''' )
if "attn.proj" in name:
A_ : Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name:
A_ : Optional[int] = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
A_ : Any = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
A_ : str = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
A_ : Tuple = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
A_ : List[str] = name.replace('''mlp.fc2''' , '''output.dense''' )
# final layernorm
if "audio_spectrogram_transformer.norm" in name:
A_ : Tuple = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' )
# classifier head
if "module.mlp_head.0" in name:
A_ : Dict = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' )
if "module.mlp_head.1" in name:
A_ : Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' )
return name
def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ):
"""simple docstring"""
for key in orig_state_dict.copy().keys():
A_ : Optional[int] = orig_state_dict.pop(_UpperCAmelCase )
if "qkv" in key:
A_ : Tuple = key.split('''.''' )
A_ : Tuple = int(key_split[3] )
A_ : List[Any] = config.hidden_size
if "weight" in key:
A_ : str = val[:dim, :]
A_ : Union[str, Any] = val[dim : dim * 2, :]
A_ : List[str] = val[-dim:, :]
else:
A_ : int = val[:dim]
A_ : Optional[Any] = val[dim : dim * 2]
A_ : Optional[int] = val[-dim:]
else:
A_ : List[str] = val
return orig_state_dict
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ : List[str] = [
'''module.v.head.weight''',
'''module.v.head.bias''',
'''module.v.head_dist.weight''',
'''module.v.head_dist.bias''',
]
for k in ignore_keys:
state_dict.pop(_UpperCAmelCase , _UpperCAmelCase )
@torch.no_grad()
def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False ):
"""simple docstring"""
A_ : Tuple = get_audio_spectrogram_transformer_config(_UpperCAmelCase )
A_ : str = {
'''ast-finetuned-audioset-10-10-0.4593''': (
'''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.450''': (
'''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448''': (
'''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'''
),
'''ast-finetuned-audioset-10-10-0.448-v2''': (
'''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'''
),
'''ast-finetuned-audioset-12-12-0.447''': (
'''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'''
),
'''ast-finetuned-audioset-14-14-0.443''': (
'''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'''
),
'''ast-finetuned-audioset-16-16-0.442''': (
'''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'''
),
'''ast-finetuned-speech-commands-v2''': (
'''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'''
),
}
# load original state_dict
A_ : Any = model_name_to_url[model_name]
A_ : str = torch.hub.load_state_dict_from_url(_UpperCAmelCase , map_location='''cpu''' )
# remove some keys
remove_keys(_UpperCAmelCase )
# rename some keys
A_ : List[Any] = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase )
# load 🤗 model
A_ : Optional[Any] = ASTForAudioClassification(_UpperCAmelCase )
model.eval()
model.load_state_dict(_UpperCAmelCase )
# verify outputs on dummy input
# source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
A_ : Optional[Any] = -4.267_7393 if '''speech-commands''' not in model_name else -6.84_5978
A_ : Dict = 4.568_9974 if '''speech-commands''' not in model_name else 5.565_4526
A_ : int = 1024 if '''speech-commands''' not in model_name else 128
A_ : List[Any] = ASTFeatureExtractor(mean=_UpperCAmelCase , std=_UpperCAmelCase , max_length=_UpperCAmelCase )
if "speech-commands" in model_name:
A_ : Union[str, Any] = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' )
A_ : List[str] = dataset[0]['''audio''']['''array''']
else:
A_ : List[Any] = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , )
A_ , A_ : Optional[int] = torchaudio.load(_UpperCAmelCase )
A_ : int = waveform.squeeze().numpy()
A_ : Any = feature_extractor(_UpperCAmelCase , sampling_rate=1_6000 , return_tensors='''pt''' )
# forward pass
A_ : Optional[Any] = model(**_UpperCAmelCase )
A_ : Optional[int] = outputs.logits
if model_name == "ast-finetuned-audioset-10-10-0.4593":
A_ : Optional[Any] = torch.tensor([-0.8760, -7.0042, -8.6602] )
elif model_name == "ast-finetuned-audioset-10-10-0.450":
A_ : Optional[Any] = torch.tensor([-1.1986, -7.0903, -8.2718] )
elif model_name == "ast-finetuned-audioset-10-10-0.448":
A_ : Tuple = torch.tensor([-2.6128, -8.0080, -9.4344] )
elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
A_ : Tuple = torch.tensor([-1.5080, -7.4534, -8.8917] )
elif model_name == "ast-finetuned-audioset-12-12-0.447":
A_ : Union[str, Any] = torch.tensor([-0.5050, -6.5833, -8.0843] )
elif model_name == "ast-finetuned-audioset-14-14-0.443":
A_ : Tuple = torch.tensor([-0.3826, -7.0336, -8.2413] )
elif model_name == "ast-finetuned-audioset-16-16-0.442":
A_ : Union[str, Any] = torch.tensor([-1.2113, -6.9101, -8.3470] )
elif model_name == "ast-finetuned-speech-commands-v2":
A_ : List[str] = torch.tensor([6.1589, -8.0566, -8.7984] )
else:
raise ValueError('''Unknown model name''' )
if not torch.allclose(logits[0, :3] , _UpperCAmelCase , atol=1E-4 ):
raise ValueError('''Logits don\'t match''' )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase )
print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(_UpperCAmelCase )
print(f"""Saving feature extractor to {pytorch_dump_folder_path}""" )
feature_extractor.save_pretrained(_UpperCAmelCase )
if push_to_hub:
print('''Pushing model and feature extractor to the hub...''' )
model.push_to_hub(f"""MIT/{model_name}""" )
feature_extractor.push_to_hub(f"""MIT/{model_name}""" )
if __name__ == "__main__":
_lowerCamelCase : Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='ast-finetuned-audioset-10-10-0.4593',
type=str,
help='Name of the Audio Spectrogram Transformer model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
_lowerCamelCase : List[Any] = parser.parse_args()
convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 361 |
"""simple docstring"""
from collections.abc import Generator
from math import sin
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
if len(_UpperCAmelCase ) != 32:
raise ValueError('''Input must be of length 32''' )
A_ : int = b''''''
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
if i < 0:
raise ValueError('''Input must be non-negative''' )
A_ : int = format(_UpperCAmelCase , '''08x''' )[-8:]
A_ : Optional[Any] = b''''''
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8''' )
return little_endian_hex
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ : int = b''''''
for char in message:
bit_string += format(_UpperCAmelCase , '''08b''' ).encode('''utf-8''' )
A_ : Optional[Any] = format(len(_UpperCAmelCase ) , '''064b''' ).encode('''utf-8''' )
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(_UpperCAmelCase ) % 512 != 448:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] )
return bit_string
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
if len(_UpperCAmelCase ) % 512 != 0:
raise ValueError('''Input must have length that\'s a multiple of 512''' )
for pos in range(0 , len(_UpperCAmelCase ) , 512 ):
A_ : Union[str, Any] = bit_string[pos : pos + 512]
A_ : Optional[int] = []
for i in range(0 , 512 , 32 ):
block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) )
yield block_words
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
if i < 0:
raise ValueError('''Input must be non-negative''' )
A_ : str = format(_UpperCAmelCase , '''032b''' )
A_ : List[str] = ''''''
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(_UpperCAmelCase , 2 )
def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ):
"""simple docstring"""
return (a + b) % 2**32
def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ):
"""simple docstring"""
if i < 0:
raise ValueError('''Input must be non-negative''' )
if shift < 0:
raise ValueError('''Shift must be non-negative''' )
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def lowercase_ ( _UpperCAmelCase ):
"""simple docstring"""
A_ : Any = preprocess(_UpperCAmelCase )
A_ : Any = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )]
# Starting states
A_ : List[str] = 0x6_7_4_5_2_3_0_1
A_ : str = 0xe_f_c_d_a_b_8_9
A_ : Union[str, Any] = 0x9_8_b_a_d_c_f_e
A_ : Dict = 0x1_0_3_2_5_4_7_6
A_ : int = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(_UpperCAmelCase ):
A_ : str = aa
A_ : Tuple = ba
A_ : Tuple = ca
A_ : int = da
# Hash current chunk
for i in range(64 ):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
A_ : str = d ^ (b & (c ^ d))
A_ : int = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
A_ : List[Any] = c ^ (d & (b ^ c))
A_ : Optional[int] = (5 * i + 1) % 16
elif i <= 47:
A_ : Optional[Any] = b ^ c ^ d
A_ : List[Any] = (3 * i + 5) % 16
else:
A_ : Dict = c ^ (b | not_aa(_UpperCAmelCase ))
A_ : Dict = (7 * i) % 16
A_ : Optional[int] = (f + a + added_consts[i] + block_words[g]) % 2**32
A_ : List[str] = d
A_ : str = c
A_ : Tuple = b
A_ : Tuple = sum_aa(_UpperCAmelCase , left_rotate_aa(_UpperCAmelCase , shift_amounts[i] ) )
# Add hashed chunk to running total
A_ : str = sum_aa(_UpperCAmelCase , _UpperCAmelCase )
A_ : int = sum_aa(_UpperCAmelCase , _UpperCAmelCase )
A_ : int = sum_aa(_UpperCAmelCase , _UpperCAmelCase )
A_ : Optional[Any] = sum_aa(_UpperCAmelCase , _UpperCAmelCase )
A_ : Dict = reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase ) + reformat_hex(_UpperCAmelCase )
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 361 | 1 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
BertTokenizer,
ViltConfig,
ViltForImageAndTextRetrieval,
ViltForImagesAndTextClassification,
ViltForMaskedLM,
ViltForQuestionAnswering,
ViltImageProcessor,
ViltProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
A_ : Union[str, Any] =logging.get_logger(__name__)
def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__=False , UpperCAmelCase__=False , UpperCAmelCase__=False ):
"""simple docstring"""
a_ = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((F"transformer.blocks.{i}.norm1.weight", F"vilt.encoder.layer.{i}.layernorm_before.weight") )
rename_keys.append((F"transformer.blocks.{i}.norm1.bias", F"vilt.encoder.layer.{i}.layernorm_before.bias") )
rename_keys.append(
(F"transformer.blocks.{i}.attn.proj.weight", F"vilt.encoder.layer.{i}.attention.output.dense.weight") )
rename_keys.append(
(F"transformer.blocks.{i}.attn.proj.bias", F"vilt.encoder.layer.{i}.attention.output.dense.bias") )
rename_keys.append((F"transformer.blocks.{i}.norm2.weight", F"vilt.encoder.layer.{i}.layernorm_after.weight") )
rename_keys.append((F"transformer.blocks.{i}.norm2.bias", F"vilt.encoder.layer.{i}.layernorm_after.bias") )
rename_keys.append(
(F"transformer.blocks.{i}.mlp.fc1.weight", F"vilt.encoder.layer.{i}.intermediate.dense.weight") )
rename_keys.append((F"transformer.blocks.{i}.mlp.fc1.bias", F"vilt.encoder.layer.{i}.intermediate.dense.bias") )
rename_keys.append((F"transformer.blocks.{i}.mlp.fc2.weight", F"vilt.encoder.layer.{i}.output.dense.weight") )
rename_keys.append((F"transformer.blocks.{i}.mlp.fc2.bias", F"vilt.encoder.layer.{i}.output.dense.bias") )
# embeddings
rename_keys.extend(
[
# text embeddings
("""text_embeddings.word_embeddings.weight""", """vilt.embeddings.text_embeddings.word_embeddings.weight"""),
(
"""text_embeddings.position_embeddings.weight""",
"""vilt.embeddings.text_embeddings.position_embeddings.weight""",
),
("""text_embeddings.position_ids""", """vilt.embeddings.text_embeddings.position_ids"""),
(
"""text_embeddings.token_type_embeddings.weight""",
"""vilt.embeddings.text_embeddings.token_type_embeddings.weight""",
),
("""text_embeddings.LayerNorm.weight""", """vilt.embeddings.text_embeddings.LayerNorm.weight"""),
("""text_embeddings.LayerNorm.bias""", """vilt.embeddings.text_embeddings.LayerNorm.bias"""),
# patch embeddings
("""transformer.cls_token""", """vilt.embeddings.cls_token"""),
("""transformer.patch_embed.proj.weight""", """vilt.embeddings.patch_embeddings.projection.weight"""),
("""transformer.patch_embed.proj.bias""", """vilt.embeddings.patch_embeddings.projection.bias"""),
("""transformer.pos_embed""", """vilt.embeddings.position_embeddings"""),
# token type embeddings
("""token_type_embeddings.weight""", """vilt.embeddings.token_type_embeddings.weight"""),
] )
# final layernorm + pooler
rename_keys.extend(
[
("""transformer.norm.weight""", """vilt.layernorm.weight"""),
("""transformer.norm.bias""", """vilt.layernorm.bias"""),
("""pooler.dense.weight""", """vilt.pooler.dense.weight"""),
("""pooler.dense.bias""", """vilt.pooler.dense.bias"""),
] )
# classifier head(s)
if vqa_model:
# classification head
rename_keys.extend(
[
("""vqa_classifier.0.weight""", """classifier.0.weight"""),
("""vqa_classifier.0.bias""", """classifier.0.bias"""),
("""vqa_classifier.1.weight""", """classifier.1.weight"""),
("""vqa_classifier.1.bias""", """classifier.1.bias"""),
("""vqa_classifier.3.weight""", """classifier.3.weight"""),
("""vqa_classifier.3.bias""", """classifier.3.bias"""),
] )
elif nlvr_model:
# classification head
rename_keys.extend(
[
("""nlvr2_classifier.0.weight""", """classifier.0.weight"""),
("""nlvr2_classifier.0.bias""", """classifier.0.bias"""),
("""nlvr2_classifier.1.weight""", """classifier.1.weight"""),
("""nlvr2_classifier.1.bias""", """classifier.1.bias"""),
("""nlvr2_classifier.3.weight""", """classifier.3.weight"""),
("""nlvr2_classifier.3.bias""", """classifier.3.bias"""),
] )
else:
pass
return rename_keys
def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
for i in range(config.num_hidden_layers ):
a_ = """vilt."""
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
a_ = state_dict.pop(F"transformer.blocks.{i}.attn.qkv.weight" )
a_ = state_dict.pop(F"transformer.blocks.{i}.attn.qkv.bias" )
# next, add query, keys and values (in that order) to the state dict
a_ = in_proj_weight[
: config.hidden_size, :
]
a_ = in_proj_bias[: config.hidden_size]
a_ = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
a_ = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
a_ = in_proj_weight[
-config.hidden_size :, :
]
a_ = in_proj_bias[-config.hidden_size :]
def lowerCamelCase_ ( UpperCAmelCase__ ):
"""simple docstring"""
a_ = ["""head.weight""", """head.bias"""]
for k in ignore_keys:
state_dict.pop(UpperCAmelCase__ , UpperCAmelCase__ )
def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
a_ = dct.pop(UpperCAmelCase__ )
a_ = val
@torch.no_grad()
def lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ ):
"""simple docstring"""
a_ = ViltConfig(image_size=384 , patch_size=32 , tie_word_embeddings=UpperCAmelCase__ )
a_ = False
a_ = False
a_ = False
a_ = False
if "vqa" in checkpoint_url:
a_ = True
a_ = 3_129
a_ = """huggingface/label-files"""
a_ = """vqa2-id2label.json"""
a_ = json.load(open(hf_hub_download(UpperCAmelCase__ , UpperCAmelCase__ , repo_type="""dataset""" ) , """r""" ) )
a_ = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()}
a_ = idalabel
a_ = {v: k for k, v in idalabel.items()}
a_ = ViltForQuestionAnswering(UpperCAmelCase__ )
elif "nlvr" in checkpoint_url:
a_ = True
a_ = 2
a_ = {0: """False""", 1: """True"""}
a_ = {v: k for k, v in config.idalabel.items()}
a_ = 3
a_ = ViltForImagesAndTextClassification(UpperCAmelCase__ )
elif "irtr" in checkpoint_url:
a_ = True
a_ = ViltForImageAndTextRetrieval(UpperCAmelCase__ )
elif "mlm_itm" in checkpoint_url:
a_ = True
a_ = ViltForMaskedLM(UpperCAmelCase__ )
else:
raise ValueError("""Unknown model type""" )
# load state_dict of original model, remove and rename some keys
a_ = torch.hub.load_state_dict_from_url(UpperCAmelCase__ , map_location="""cpu""" )["""state_dict"""]
a_ = create_rename_keys(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
for src, dest in rename_keys:
rename_key(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
read_in_q_k_v(UpperCAmelCase__ , UpperCAmelCase__ )
if mlm_model or irtr_model:
a_ = ["""itm_score.fc.weight""", """itm_score.fc.bias"""]
for k in ignore_keys:
state_dict.pop(UpperCAmelCase__ , UpperCAmelCase__ )
# load state dict into HuggingFace model
model.eval()
if mlm_model:
a_ , a_ = model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ )
assert missing_keys == ["mlm_score.decoder.bias"]
else:
model.load_state_dict(UpperCAmelCase__ )
# Define processor
a_ = ViltImageProcessor(size=384 )
a_ = BertTokenizer.from_pretrained("""bert-base-uncased""" )
a_ = ViltProcessor(UpperCAmelCase__ , UpperCAmelCase__ )
# Forward pass on example inputs (image + text)
if nlvr_model:
a_ = Image.open(requests.get("""https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg""" , stream=UpperCAmelCase__ ).raw )
a_ = Image.open(requests.get("""https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg""" , stream=UpperCAmelCase__ ).raw )
a_ = (
"""The left image contains twice the number of dogs as the right image, and at least two dogs in total are"""
""" standing."""
)
a_ = processor(UpperCAmelCase__ , UpperCAmelCase__ , return_tensors="""pt""" )
a_ = processor(UpperCAmelCase__ , UpperCAmelCase__ , return_tensors="""pt""" )
a_ = model(
input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , )
else:
a_ = Image.open(requests.get("""http://images.cocodataset.org/val2017/000000039769.jpg""" , stream=UpperCAmelCase__ ).raw )
if mlm_model:
a_ = """a bunch of [MASK] laying on a [MASK]."""
else:
a_ = """How many cats are there?"""
a_ = processor(UpperCAmelCase__ , UpperCAmelCase__ , return_tensors="""pt""" )
a_ = model(**UpperCAmelCase__ )
# Verify outputs
if mlm_model:
a_ = torch.Size([1, 11, 30_522] )
a_ = torch.tensor([-12.50_61, -12.51_23, -12.51_74] )
assert outputs.logits.shape == expected_shape
assert torch.allclose(outputs.logits[0, 0, :3] , UpperCAmelCase__ , atol=1e-4 )
# verify masked token prediction equals "cats"
a_ = outputs.logits[0, 4, :].argmax(-1 ).item()
assert tokenizer.decode([predicted_id] ) == "cats"
elif vqa_model:
a_ = torch.Size([1, 3_129] )
a_ = torch.tensor([-15.94_95, -18.14_72, -10.30_41] )
assert torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1e-4 )
assert outputs.logits.shape == expected_shape
assert torch.allclose(outputs.logits[0, 0, :3] , UpperCAmelCase__ , atol=1e-4 )
# verify vqa prediction equals "2"
a_ = outputs.logits.argmax(-1 ).item()
assert model.config.idalabel[predicted_idx] == "2"
elif nlvr_model:
a_ = torch.Size([1, 2] )
a_ = torch.tensor([-2.87_21, 2.12_91] )
assert torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1e-4 )
assert outputs.logits.shape == expected_shape
Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ )
print(F"Saving model and processor to {pytorch_dump_folder_path}" )
model.save_pretrained(UpperCAmelCase__ )
processor.save_pretrained(UpperCAmelCase__ )
if __name__ == "__main__":
A_ : Union[str, Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--checkpoint_url""",
default="""https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt""",
type=str,
help="""URL of the checkpoint you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
A_ : Union[str, Any] =parser.parse_args()
convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path) | 483 |
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer
import datasets
from datasets import logging
A_ : List[Any] ="""\
"""
A_ : Optional[Any] ="""
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.
For more information, see https://huggingface.co/docs/transformers/perplexity
"""
A_ : Any ="""
Args:
model_id (str): model used for calculating Perplexity
NOTE: Perplexity can only be calculated for causal language models.
This includes models such as gpt2, causal variations of bert,
causal versions of t5, and more (the full list can be found
in the AutoModelForCausalLM documentation here:
https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )
input_texts (list of str): input text, each separate text snippet
is one list entry.
batch_size (int): the batch size to run texts through the model. Defaults to 16.
add_start_token (bool): whether to add the start token to the texts,
so the perplexity can include the probability of the first word. Defaults to True.
device (str): device to run on, defaults to 'cuda' when available
Returns:
perplexity: dictionary containing the perplexity scores for the texts
in the input list, as well as the mean perplexity. If one of the input texts is
longer than the max input length of the model, then it is truncated to the
max length for the perplexity computation.
Examples:
Example 1:
>>> perplexity = datasets.load_metric(\"perplexity\")
>>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]
>>> results = perplexity.compute(model_id='gpt2',
... add_start_token=False,
... input_texts=input_texts) # doctest:+ELLIPSIS
>>> print(list(results.keys()))
['perplexities', 'mean_perplexity']
>>> print(round(results[\"mean_perplexity\"], 2))
78.22
>>> print(round(results[\"perplexities\"][0], 2))
11.11
Example 2:
>>> perplexity = datasets.load_metric(\"perplexity\")
>>> input_texts = datasets.load_dataset(\"wikitext\",
... \"wikitext-2-raw-v1\",
... split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS
[...]
>>> input_texts = [s for s in input_texts if s!='']
>>> results = perplexity.compute(model_id='gpt2',
... input_texts=input_texts) # doctest:+ELLIPSIS
>>> print(list(results.keys()))
['perplexities', 'mean_perplexity']
>>> print(round(results[\"mean_perplexity\"], 2))
60.35
>>> print(round(results[\"perplexities\"][0], 2))
81.12
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION)
class lowercase_ ( datasets.Metric):
"""simple docstring"""
def lowercase__ ( self ):
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""input_texts""": datasets.Value("""string""" ),
} ) , reference_urls=["""https://huggingface.co/docs/transformers/perplexity"""] , )
def lowercase__ ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 16 , _UpperCAmelCase = True , _UpperCAmelCase=None ):
"""simple docstring"""
if device is not None:
assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
if device == "gpu":
a_ = """cuda"""
else:
a_ = """cuda""" if torch.cuda.is_available() else """cpu"""
a_ = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase )
a_ = model.to(_UpperCAmelCase )
a_ = AutoTokenizer.from_pretrained(_UpperCAmelCase )
# if batch_size > 1 (which generally leads to padding being required), and
# if there is not an already assigned pad_token, assign an existing
# special token to also be the padding token
if tokenizer.pad_token is None and batch_size > 1:
a_ = list(tokenizer.special_tokens_map_extended.values() )
# check that the model already has at least one special token defined
assert (
len(_UpperCAmelCase ) > 0
), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
# assign one of the special tokens to also be the pad token
tokenizer.add_special_tokens({"""pad_token""": existing_special_tokens[0]} )
if add_start_token:
# leave room for <BOS> token to be added:
assert (
tokenizer.bos_token is not None
), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
a_ = model.config.max_length - 1
else:
a_ = model.config.max_length
a_ = tokenizer(
_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase , return_tensors="""pt""" , return_attention_mask=_UpperCAmelCase , ).to(_UpperCAmelCase )
a_ = encodings["""input_ids"""]
a_ = encodings["""attention_mask"""]
# check that each input is long enough:
if add_start_token:
assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long."
else:
assert torch.all(
torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."
a_ = []
a_ = CrossEntropyLoss(reduction="""none""" )
for start_index in logging.tqdm(range(0 , len(_UpperCAmelCase ) , _UpperCAmelCase ) ):
a_ = min(start_index + batch_size , len(_UpperCAmelCase ) )
a_ = encoded_texts[start_index:end_index]
a_ = attn_masks[start_index:end_index]
if add_start_token:
a_ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(_UpperCAmelCase )
a_ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 )
a_ = torch.cat(
[torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(_UpperCAmelCase ), attn_mask] , dim=1 )
a_ = encoded_batch
with torch.no_grad():
a_ = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase ).logits
a_ = out_logits[..., :-1, :].contiguous()
a_ = labels[..., 1:].contiguous()
a_ = attn_mask[..., 1:].contiguous()
a_ = torch.expa(
(loss_fct(shift_logits.transpose(1 , 2 ) , _UpperCAmelCase ) * shift_attention_mask_batch).sum(1 )
/ shift_attention_mask_batch.sum(1 ) )
ppls += perplexity_batch.tolist()
return {"perplexities": ppls, "mean_perplexity": np.mean(_UpperCAmelCase )} | 483 | 1 |
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
_lowerCamelCase : List[Any] = Lock()
def __lowerCamelCase (UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ):
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0 , 1_0 ):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(UpperCAmelCase__ )
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
SCREAMING_SNAKE_CASE = min(UpperCAmelCase__ , UpperCAmelCase__ )
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(UpperCAmelCase__ )
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
SCREAMING_SNAKE_CASE = max(UpperCAmelCase__ , UpperCAmelCase__ )
# after all swaps are performed, send the values back to main
result_pipe[1].send(UpperCAmelCase__ )
def __lowerCamelCase (UpperCAmelCase__ : List[Any] ):
SCREAMING_SNAKE_CASE = []
SCREAMING_SNAKE_CASE = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe() )
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
SCREAMING_SNAKE_CASE = Pipe()
SCREAMING_SNAKE_CASE = Pipe()
process_array_.append(
Process(
target=UpperCAmelCase__ , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) )
SCREAMING_SNAKE_CASE = temp_rs
SCREAMING_SNAKE_CASE = temp_rr
for i in range(1 , len(UpperCAmelCase__ ) - 1 ):
SCREAMING_SNAKE_CASE = Pipe()
SCREAMING_SNAKE_CASE = Pipe()
process_array_.append(
Process(
target=UpperCAmelCase__ , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) )
SCREAMING_SNAKE_CASE = temp_rs
SCREAMING_SNAKE_CASE = temp_rr
process_array_.append(
Process(
target=UpperCAmelCase__ , args=(
len(UpperCAmelCase__ ) - 1,
arr[len(UpperCAmelCase__ ) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(UpperCAmelCase__ ) - 1],
) , ) )
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0 , len(UpperCAmelCase__ ) ):
SCREAMING_SNAKE_CASE = result_pipe[p][0].recv()
process_array_[p].join()
return arr
def __lowerCamelCase ():
SCREAMING_SNAKE_CASE = list(range(1_0 , 0 , -1 ) )
print("Initial List" )
print(*UpperCAmelCase__ )
SCREAMING_SNAKE_CASE = odd_even_transposition(UpperCAmelCase__ )
print("Sorted List\n" )
print(*UpperCAmelCase__ )
if __name__ == "__main__":
main()
| 709 | # coding=utf-8
# Copyright 2023 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# this script dumps information about the environment
import os
import platform
import sys
_lowerCamelCase : List[Any] = '''3'''
print('''Python version:''', sys.version)
print('''OS platform:''', platform.platform())
print('''OS architecture:''', platform.machine())
try:
import torch
print('''Torch version:''', torch.__version__)
print('''Cuda available:''', torch.cuda.is_available())
print('''Cuda version:''', torch.version.cuda)
print('''CuDNN version:''', torch.backends.cudnn.version())
print('''Number of GPUs available:''', torch.cuda.device_count())
except ImportError:
print('''Torch version:''', None)
try:
import transformers
print('''transformers version:''', transformers.__version__)
except ImportError:
print('''transformers version:''', None)
| 647 | 0 |
"""simple docstring"""
import gc
import unittest
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DDPMScheduler,
PriorTransformer,
StableUnCLIPPipeline,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import (
PipelineKarrasSchedulerTesterMixin,
PipelineLatentTesterMixin,
PipelineTesterMixin,
assert_mean_pixel_difference,
)
enable_full_determinism()
class lowercase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase : Optional[int] = StableUnCLIPPipeline
UpperCAmelCase : List[Any] = TEXT_TO_IMAGE_PARAMS
UpperCAmelCase : int = TEXT_TO_IMAGE_BATCH_PARAMS
UpperCAmelCase : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS
UpperCAmelCase : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS
# TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
UpperCAmelCase : Dict = False
def lowerCAmelCase_ ( self : Union[str, Any] ):
_A = 32
_A = embedder_hidden_size
# prior components
torch.manual_seed(0 )
_A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
torch.manual_seed(0 )
_A = CLIPTextModelWithProjection(
CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=_UpperCAmelCase , projection_dim=_UpperCAmelCase , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) )
torch.manual_seed(0 )
_A = PriorTransformer(
num_attention_heads=2 , attention_head_dim=12 , embedding_dim=_UpperCAmelCase , num_layers=1 , )
torch.manual_seed(0 )
_A = DDPMScheduler(
variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1_000 , clip_sample=_UpperCAmelCase , clip_sample_range=5.0 , beta_schedule='squaredcos_cap_v2' , )
# regular denoising components
torch.manual_seed(0 )
_A = StableUnCLIPImageNormalizer(embedding_dim=_UpperCAmelCase )
_A = DDPMScheduler(beta_schedule='squaredcos_cap_v2' )
torch.manual_seed(0 )
_A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
torch.manual_seed(0 )
_A = CLIPTextModel(
CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=_UpperCAmelCase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) )
torch.manual_seed(0 )
_A = UNetaDConditionModel(
sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_UpperCAmelCase , layers_per_block=1 , upcast_attention=_UpperCAmelCase , use_linear_projection=_UpperCAmelCase , )
torch.manual_seed(0 )
_A = DDIMScheduler(
beta_schedule='scaled_linear' , beta_start=0.0_0085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=_UpperCAmelCase , steps_offset=1 , )
torch.manual_seed(0 )
_A = AutoencoderKL()
_A = {
# prior components
'prior_tokenizer': prior_tokenizer,
'prior_text_encoder': prior_text_encoder,
'prior': prior,
'prior_scheduler': prior_scheduler,
# image noising components
'image_normalizer': image_normalizer,
'image_noising_scheduler': image_noising_scheduler,
# regular denoising components
'tokenizer': tokenizer,
'text_encoder': text_encoder,
'unet': unet,
'scheduler': scheduler,
'vae': vae,
}
return components
def lowerCAmelCase_ ( self : int , _UpperCAmelCase : Tuple , _UpperCAmelCase : List[Any]=0 ):
if str(_UpperCAmelCase ).startswith('mps' ):
_A = torch.manual_seed(_UpperCAmelCase )
else:
_A = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase )
_A = {
'prompt': 'A painting of a squirrel eating a burger',
'generator': generator,
'num_inference_steps': 2,
'prior_num_inference_steps': 2,
'output_type': 'numpy',
}
return inputs
def lowerCAmelCase_ ( self : str ):
_A = torch_device == 'cpu'
self._test_attention_slicing_forward_pass(test_max_difference=_UpperCAmelCase )
def lowerCAmelCase_ ( self : str ):
_A = torch_device in ['cpu', 'mps']
self._test_inference_batch_single_identical(test_max_difference=_UpperCAmelCase )
@slow
@require_torch_gpu
class lowercase_ ( unittest.TestCase ):
'''simple docstring'''
def lowerCAmelCase_ ( self : Optional[Any] ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowerCAmelCase_ ( self : Dict ):
_A = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy' )
_A = StableUnCLIPPipeline.from_pretrained('fusing/stable-unclip-2-1-l' , torch_dtype=torch.floataa )
pipe.to(_UpperCAmelCase )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
# stable unclip will oom when integration tests are run on a V100,
# so turn on memory savings
pipe.enable_attention_slicing()
pipe.enable_sequential_cpu_offload()
_A = torch.Generator(device='cpu' ).manual_seed(0 )
_A = pipe('anime turle' , generator=_UpperCAmelCase , output_type='np' )
_A = output.images[0]
assert image.shape == (768, 768, 3)
assert_mean_pixel_difference(_UpperCAmelCase , _UpperCAmelCase )
def lowerCAmelCase_ ( self : Tuple ):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
_A = StableUnCLIPPipeline.from_pretrained('fusing/stable-unclip-2-1-l' , torch_dtype=torch.floataa )
_A = pipe.to(_UpperCAmelCase )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
pipe.enable_attention_slicing()
pipe.enable_sequential_cpu_offload()
_A = pipe(
'anime turtle' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='np' , )
_A = torch.cuda.max_memory_allocated()
# make sure that less than 7 GB is allocated
assert mem_bytes < 7 * 10**9
| 7 |
"""simple docstring"""
import copy
import json
import os
import tempfile
from transformers import is_torch_available
from .test_configuration_utils import config_common_kwargs
class _snake_case ( A__ ):
'''simple docstring'''
def __init__( self : Optional[Any] , snake_case : int , snake_case : Tuple=None , snake_case : List[Any]=True , snake_case : int=None , **snake_case : Any ):
UpperCAmelCase_ :str = parent
UpperCAmelCase_ :Tuple = config_class
UpperCAmelCase_ :Optional[int] = has_text_modality
UpperCAmelCase_ :int = kwargs
UpperCAmelCase_ :Any = common_properties
def snake_case_ ( self : Optional[int] ):
UpperCAmelCase_ :int = self.config_class(**self.inputs_dict )
UpperCAmelCase_ :List[Any] = (
['''hidden_size''', '''num_attention_heads''', '''num_hidden_layers''']
if self.common_properties is None
else self.common_properties
)
# Add common fields for text models
if self.has_text_modality:
common_properties.extend(['''vocab_size'''] )
# Test that config has the common properties as getters
for prop in common_properties:
self.parent.assertTrue(hasattr(snake_case , snake_case ) , msg=f'`{prop}` does not exist' )
# Test that config has the common properties as setter
for idx, name in enumerate(snake_case ):
try:
setattr(snake_case , snake_case , snake_case )
self.parent.assertEqual(
getattr(snake_case , snake_case ) , snake_case , msg=f'`{name} value {idx} expected, but was {getattr(snake_case , snake_case )}' )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
# Test if config class can be called with Config(prop_name=..)
for idx, name in enumerate(snake_case ):
try:
UpperCAmelCase_ :Tuple = self.config_class(**{name: idx} )
self.parent.assertEqual(
getattr(snake_case , snake_case ) , snake_case , msg=f'`{name} value {idx} expected, but was {getattr(snake_case , snake_case )}' )
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
def snake_case_ ( self : int ):
UpperCAmelCase_ :Union[str, Any] = self.config_class(**self.inputs_dict )
UpperCAmelCase_ :Optional[Any] = json.loads(config.to_json_string() )
for key, value in self.inputs_dict.items():
self.parent.assertEqual(obj[key] , snake_case )
def snake_case_ ( self : Optional[Any] ):
UpperCAmelCase_ :List[str] = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ :Dict = os.path.join(snake_case , '''config.json''' )
config_first.to_json_file(snake_case )
UpperCAmelCase_ :Union[str, Any] = self.config_class.from_json_file(snake_case )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def snake_case_ ( self : Any ):
UpperCAmelCase_ :Optional[Any] = self.config_class(**self.inputs_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
config_first.save_pretrained(snake_case )
UpperCAmelCase_ :Union[str, Any] = self.config_class.from_pretrained(snake_case )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def snake_case_ ( self : Optional[int] ):
UpperCAmelCase_ :List[Any] = self.config_class(**self.inputs_dict )
UpperCAmelCase_ :Dict = '''test'''
with tempfile.TemporaryDirectory() as tmpdirname:
UpperCAmelCase_ :List[str] = os.path.join(snake_case , snake_case )
config_first.save_pretrained(snake_case )
UpperCAmelCase_ :Optional[int] = self.config_class.from_pretrained(snake_case , subfolder=snake_case )
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() )
def snake_case_ ( self : List[str] ):
UpperCAmelCase_ :Dict = self.config_class(**self.inputs_dict , num_labels=5 )
self.parent.assertEqual(len(config.idalabel ) , 5 )
self.parent.assertEqual(len(config.labelaid ) , 5 )
UpperCAmelCase_ :List[str] = 3
self.parent.assertEqual(len(config.idalabel ) , 3 )
self.parent.assertEqual(len(config.labelaid ) , 3 )
def snake_case_ ( self : int ):
if self.config_class.is_composition:
return
UpperCAmelCase_ :int = self.config_class()
self.parent.assertIsNotNone(snake_case )
def snake_case_ ( self : int ):
UpperCAmelCase_ :str = copy.deepcopy(snake_case )
UpperCAmelCase_ :Optional[Any] = self.config_class(**snake_case )
UpperCAmelCase_ :Optional[Any] = []
for key, value in config_common_kwargs.items():
if key == "torch_dtype":
if not is_torch_available():
continue
else:
import torch
if config.torch_dtype != torch.floataa:
wrong_values.append(('''torch_dtype''', config.torch_dtype, torch.floataa) )
elif getattr(snake_case , snake_case ) != value:
wrong_values.append((key, getattr(snake_case , snake_case ), value) )
if len(snake_case ) > 0:
UpperCAmelCase_ :int = '''\n'''.join([f'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values] )
raise ValueError(f'The following keys were not properly set in the config:\n{errors}' )
def snake_case_ ( self : int ):
self.create_and_test_config_common_properties()
self.create_and_test_config_to_json_string()
self.create_and_test_config_to_json_file()
self.create_and_test_config_from_and_save_pretrained()
self.create_and_test_config_from_and_save_pretrained_subfolder()
self.create_and_test_config_with_num_labels()
self.check_config_can_be_init_without_params()
self.check_config_arguments_init()
| 608 | 0 |
import enum
import warnings
from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_tf_available():
import tensorflow as tf
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
SCREAMING_SNAKE_CASE_:List[str] = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE__ ( enum.Enum ):
'''simple docstring'''
__lowerCamelCase : List[Any] = 0
__lowerCamelCase : Union[str, Any] = 1
@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
__lowerCamelCase : Optional[int] = "generated"
def __init__( self, *lowerCamelCase__, **lowerCamelCase__ ):
super().__init__(*lowerCamelCase__, **lowerCamelCase__ )
self.check_model_type(
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
if self.framework == """tf"""
else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING )
def _lowerCAmelCase ( self, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__=None, **lowerCamelCase__, ):
A : Optional[Any] = {}
if truncation is not None:
A : Dict = truncation
A : int = generate_kwargs
A : Tuple = {}
if return_tensors is not None and return_type is None:
A : str = ReturnType.TENSORS if return_tensors else ReturnType.TEXT
if return_type is not None:
A : Optional[int] = return_type
if clean_up_tokenization_spaces is not None:
A : Tuple = clean_up_tokenization_spaces
if stop_sequence is not None:
A : Optional[int] = self.tokenizer.encode(lowerCamelCase__, add_special_tokens=lowerCamelCase__ )
if len(lowerCamelCase__ ) > 1:
warnings.warn(
"""Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
""" the stop sequence will be used as the stop sequence string in the interim.""" )
A : Tuple = stop_sequence_ids[0]
return preprocess_params, forward_params, postprocess_params
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ):
return True
def _lowerCAmelCase ( self, *lowerCamelCase__, lowerCamelCase__ ):
A : Dict = self.model.config.prefix if self.model.config.prefix is not None else """"""
if isinstance(args[0], lowerCamelCase__ ):
if self.tokenizer.pad_token_id is None:
raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input""" )
A : Optional[int] = ([prefix + arg for arg in args[0]],)
A : Optional[int] = True
elif isinstance(args[0], lowerCamelCase__ ):
A : Optional[Any] = (prefix + args[0],)
A : Tuple = False
else:
raise ValueError(
f''' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`''' )
A : Union[str, Any] = self.tokenizer(*lowerCamelCase__, padding=lowerCamelCase__, truncation=lowerCamelCase__, return_tensors=self.framework )
# This is produced by tokenizers but is an invalid generate kwargs
if "token_type_ids" in inputs:
del inputs["token_type_ids"]
return inputs
def __call__( self, *lowerCamelCase__, **lowerCamelCase__ ):
A : List[str] = super().__call__(*lowerCamelCase__, **lowerCamelCase__ )
if (
isinstance(args[0], lowerCamelCase__ )
and all(isinstance(lowerCamelCase__, lowerCamelCase__ ) for el in args[0] )
and all(len(lowerCamelCase__ ) == 1 for res in result )
):
return [res[0] for res in result]
return result
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__=TruncationStrategy.DO_NOT_TRUNCATE, **lowerCamelCase__ ):
A : Optional[int] = self._parse_and_tokenize(lowerCamelCase__, truncation=lowerCamelCase__, **lowerCamelCase__ )
return inputs
def _lowerCAmelCase ( self, lowerCamelCase__, **lowerCamelCase__ ):
if self.framework == "pt":
A , A : Optional[int] = model_inputs["""input_ids"""].shape
elif self.framework == "tf":
A , A : Tuple = tf.shape(model_inputs["""input_ids"""] ).numpy()
A : Union[str, Any] = generate_kwargs.get("""min_length""", self.model.config.min_length )
A : Any = generate_kwargs.get("""max_length""", self.model.config.max_length )
self.check_inputs(lowerCamelCase__, generate_kwargs["""min_length"""], generate_kwargs["""max_length"""] )
A : int = self.model.generate(**lowerCamelCase__, **lowerCamelCase__ )
A : Union[str, Any] = output_ids.shape[0]
if self.framework == "pt":
A : Dict = output_ids.reshape(lowerCamelCase__, out_b // in_b, *output_ids.shape[1:] )
elif self.framework == "tf":
A : Union[str, Any] = tf.reshape(lowerCamelCase__, (in_b, out_b // in_b, *output_ids.shape[1:]) )
return {"output_ids": output_ids}
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__=ReturnType.TEXT, lowerCamelCase__=False ):
A : int = []
for output_ids in model_outputs["output_ids"][0]:
if return_type == ReturnType.TENSORS:
A : List[str] = {f'''{self.return_name}_token_ids''': output_ids}
elif return_type == ReturnType.TEXT:
A : str = {
f'''{self.return_name}_text''': self.tokenizer.decode(
lowerCamelCase__, skip_special_tokens=lowerCamelCase__, clean_up_tokenization_spaces=lowerCamelCase__, )
}
records.append(lowerCamelCase__ )
return records
@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
__lowerCamelCase : List[Any] = "summary"
def __call__( self, *lowerCamelCase__, **lowerCamelCase__ ):
return super().__call__(*lowerCamelCase__, **lowerCamelCase__ )
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ):
if max_length < min_length:
logger.warning(f'''Your min_length={min_length} must be inferior than your max_length={max_length}.''' )
if input_length < max_length:
logger.warning(
f'''Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '''
"""a summarization task, where outputs shorter than the input are typically wanted, you might """
f'''consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})''' )
@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
__lowerCamelCase : List[Any] = "translation"
def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ):
if input_length > 0.9 * max_length:
logger.warning(
f'''Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '''
"""increasing your max_length manually, e.g. translator('...', max_length=400)""" )
return True
def _lowerCAmelCase ( self, *lowerCamelCase__, lowerCamelCase__=TruncationStrategy.DO_NOT_TRUNCATE, lowerCamelCase__=None, lowerCamelCase__=None ):
if getattr(self.tokenizer, """_build_translation_inputs""", lowerCamelCase__ ):
return self.tokenizer._build_translation_inputs(
*lowerCamelCase__, return_tensors=self.framework, truncation=lowerCamelCase__, src_lang=lowerCamelCase__, tgt_lang=lowerCamelCase__ )
else:
return super()._parse_and_tokenize(*lowerCamelCase__, truncation=lowerCamelCase__ )
def _lowerCAmelCase ( self, lowerCamelCase__=None, lowerCamelCase__=None, **lowerCamelCase__ ):
A , A , A : Optional[Any] = super()._sanitize_parameters(**lowerCamelCase__ )
if src_lang is not None:
A : Tuple = src_lang
if tgt_lang is not None:
A : Optional[Any] = tgt_lang
if src_lang is None and tgt_lang is None:
# Backward compatibility, direct arguments use is preferred.
A : Any = kwargs.get("""task""", self.task )
A : Tuple = task.split("""_""" )
if task and len(lowerCamelCase__ ) == 4:
# translation, XX, to YY
A : Optional[Any] = items[1]
A : Any = items[3]
return preprocess_params, forward_params, postprocess_params
def __call__( self, *lowerCamelCase__, **lowerCamelCase__ ):
return super().__call__(*lowerCamelCase__, **lowerCamelCase__ )
| 520 |
from math import sqrt
def __UpperCamelCase ( _lowerCAmelCase ) -> int:
"""simple docstring"""
A : List[str] = 0
for i in range(1 , int(sqrt(_lowerCAmelCase ) + 1 ) ):
if n % i == 0 and i != sqrt(_lowerCAmelCase ):
total += i + n // i
elif i == sqrt(_lowerCAmelCase ):
total += i
return total - n
def __UpperCamelCase ( _lowerCAmelCase = 1_0000 ) -> int:
"""simple docstring"""
A : int = sum(
i
for i in range(1 , _lowerCAmelCase )
if sum_of_divisors(sum_of_divisors(_lowerCAmelCase ) ) == i and sum_of_divisors(_lowerCAmelCase ) != i )
return total
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 520 | 1 |
from dataclasses import dataclass
from typing import Optional
import torch
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .modeling_utils import ModelMixin
@dataclass
class __a ( UpperCAmelCase ):
_a : torch.FloatTensor
class __a ( UpperCAmelCase , UpperCAmelCase ):
@register_to_config
def __init__( self , _SCREAMING_SNAKE_CASE = 16 , _SCREAMING_SNAKE_CASE = 88 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = 32 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "geglu" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , ) -> Dict:
"""simple docstring"""
super().__init__()
_UpperCAmelCase = num_attention_heads
_UpperCAmelCase = attention_head_dim
_UpperCAmelCase = num_attention_heads * attention_head_dim
_UpperCAmelCase = in_channels
_UpperCAmelCase = torch.nn.GroupNorm(num_groups=_SCREAMING_SNAKE_CASE , num_channels=_SCREAMING_SNAKE_CASE , eps=1e-6 , affine=_SCREAMING_SNAKE_CASE )
_UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# 3. Define transformers blocks
_UpperCAmelCase = nn.ModuleList(
[
BasicTransformerBlock(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dropout=_SCREAMING_SNAKE_CASE , cross_attention_dim=_SCREAMING_SNAKE_CASE , activation_fn=_SCREAMING_SNAKE_CASE , attention_bias=_SCREAMING_SNAKE_CASE , double_self_attention=_SCREAMING_SNAKE_CASE , norm_elementwise_affine=_SCREAMING_SNAKE_CASE , )
for d in range(_SCREAMING_SNAKE_CASE )
] )
_UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE = True , ) -> Tuple:
"""simple docstring"""
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = hidden_states.shape
_UpperCAmelCase = batch_frames // num_frames
_UpperCAmelCase = hidden_states
_UpperCAmelCase = hidden_states[None, :].reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
_UpperCAmelCase = hidden_states.permute(0 , 2 , 1 , 3 , 4 )
_UpperCAmelCase = self.norm(_SCREAMING_SNAKE_CASE )
_UpperCAmelCase = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
_UpperCAmelCase = self.proj_in(_SCREAMING_SNAKE_CASE )
# 2. Blocks
for block in self.transformer_blocks:
_UpperCAmelCase = block(
_SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , cross_attention_kwargs=_SCREAMING_SNAKE_CASE , class_labels=_SCREAMING_SNAKE_CASE , )
# 3. Output
_UpperCAmelCase = self.proj_out(_SCREAMING_SNAKE_CASE )
_UpperCAmelCase = (
hidden_states[None, None, :]
.reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
.permute(0 , 3 , 4 , 1 , 2 )
.contiguous()
)
_UpperCAmelCase = hidden_states.reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
_UpperCAmelCase = hidden_states + residual
if not return_dict:
return (output,)
return TransformerTemporalModelOutput(sample=_SCREAMING_SNAKE_CASE )
| 618 |
def lowerCAmelCase__ ( a__: list ) -> list:
'''simple docstring'''
if len(a__ ) < 2:
return collection
def circle_sort_util(a__: list , a__: int , a__: int ) -> bool:
_UpperCAmelCase = False
if low == high:
return swapped
_UpperCAmelCase = low
_UpperCAmelCase = high
while left < right:
if collection[left] > collection[right]:
_UpperCAmelCase , _UpperCAmelCase = (
collection[right],
collection[left],
)
_UpperCAmelCase = True
left += 1
right -= 1
if left == right and collection[left] > collection[right + 1]:
_UpperCAmelCase , _UpperCAmelCase = (
collection[right + 1],
collection[left],
)
_UpperCAmelCase = True
_UpperCAmelCase = low + int((high - low) / 2 )
_UpperCAmelCase = circle_sort_util(a__ , a__ , a__ )
_UpperCAmelCase = circle_sort_util(a__ , mid + 1 , a__ )
return swapped or left_swap or right_swap
_UpperCAmelCase = True
while is_not_sorted is True:
_UpperCAmelCase = circle_sort_util(a__ , 0 , len(a__ ) - 1 )
return collection
if __name__ == "__main__":
lowerCAmelCase__ :Tuple = input('''Enter numbers separated by a comma:\n''').strip()
lowerCAmelCase__ :List[str] = [int(item) for item in user_input.split(''',''')]
print(circle_sort(unsorted))
| 618 | 1 |
from __future__ import annotations
lowerCamelCase__ = list[list[int]]
# assigning initial values to the grid
lowerCamelCase__ = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
# a grid with no solution
lowerCamelCase__ = [
[5, 0, 6, 5, 0, 8, 4, 0, 3],
[5, 2, 0, 0, 0, 0, 0, 0, 2],
[1, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
def UpperCamelCase ( snake_case__ : Matrix ,snake_case__ : int ,snake_case__ : int ,snake_case__ : int ):
'''simple docstring'''
for i in range(9 ):
if grid[row][i] == n or grid[i][column] == n:
return False
for i in range(3 ):
for j in range(3 ):
if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
return False
return True
def UpperCamelCase ( snake_case__ : Matrix ):
'''simple docstring'''
for i in range(9 ):
for j in range(9 ):
if grid[i][j] == 0:
return i, j
return None
def UpperCamelCase ( snake_case__ : Matrix ):
'''simple docstring'''
if location := find_empty_location(snake_case__ ):
__snake_case , __snake_case :Optional[int] = location
else:
# If the location is ``None``, then the grid is solved.
return grid
for digit in range(1 ,10 ):
if is_safe(snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ):
__snake_case :Union[str, Any] = digit
if sudoku(snake_case__ ) is not None:
return grid
__snake_case :Tuple = 0
return None
def UpperCamelCase ( snake_case__ : Matrix ):
'''simple docstring'''
for row in grid:
for cell in row:
print(snake_case__ ,end=""" """ )
print()
if __name__ == "__main__":
# make a copy of grid so that you can compare with the unmodified grid
for example_grid in (initial_grid, no_solution):
print("""\nExample grid:\n""" + """=""" * 20)
print_solution(example_grid)
print("""\nExample grid solution:""")
lowerCamelCase__ = sudoku(example_grid)
if solution is not None:
print_solution(solution)
else:
print("""Cannot find a solution.""")
| 291 |
# 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,
)
lowerCamelCase__ = """pytorch_model.bin"""
lowerCamelCase__ = """pytorch_model.bin.index.json"""
lowerCamelCase__ = """adapter_config.json"""
lowerCamelCase__ = """adapter_model.bin"""
lowerCamelCase__ = """adapter_model.safetensors"""
lowerCamelCase__ = """tf_model.h5"""
lowerCamelCase__ = """tf_model.h5.index.json"""
lowerCamelCase__ = """model.ckpt"""
lowerCamelCase__ = """flax_model.msgpack"""
lowerCamelCase__ = """flax_model.msgpack.index.json"""
lowerCamelCase__ = """model.safetensors"""
lowerCamelCase__ = """model.safetensors.index.json"""
lowerCamelCase__ = """config.json"""
lowerCamelCase__ = """preprocessor_config.json"""
lowerCamelCase__ = FEATURE_EXTRACTOR_NAME
lowerCamelCase__ = """generation_config.json"""
lowerCamelCase__ = """modelcard.json"""
lowerCamelCase__ = """▁"""
lowerCamelCase__ = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility
lowerCamelCase__ = [
[[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too.
lowerCamelCase__ = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
lowerCamelCase__ = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]
def UpperCamelCase ( snake_case__ : Dict ):
'''simple docstring'''
if version.parse(snake_case__ ) < version.parse(snake_case__ ):
if "dev" in min_version:
__snake_case :Tuple = (
"""This example requires a source install from HuggingFace Transformers (see """
"""`https://huggingface.co/docs/transformers/installation#install-from-source`),"""
)
else:
__snake_case :List[str] = 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.""" )
| 291 | 1 |
import random
import unittest
import torch
from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device
from ..pipeline_params import (
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class UpperCamelCase_ ( snake_case__ , snake_case__ , unittest.TestCase ):
_a : List[Any] = IFInpaintingSuperResolutionPipeline
_a : Union[str, Any] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'}
_a : List[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'original_image'} )
_a : Optional[Any] = PipelineTesterMixin.required_optional_params - {'latents'}
def __a ( self : str ):
return self._get_superresolution_dummy_components()
def __a ( self : Any , lowerCamelCase : int , lowerCamelCase : Tuple=0 ):
if str(lowerCamelCase ).startswith('mps' ):
lowerCamelCase_ : List[Any] = torch.manual_seed(lowerCamelCase )
else:
lowerCamelCase_ : Any = torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase )
lowerCamelCase_ : int = floats_tensor((1, 3, 16, 16) , rng=random.Random(lowerCamelCase ) ).to(lowerCamelCase )
lowerCamelCase_ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase ) ).to(lowerCamelCase )
lowerCamelCase_ : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase ) ).to(lowerCamelCase )
lowerCamelCase_ : List[Any] = {
'prompt': 'A painting of a squirrel eating a burger',
'image': image,
'original_image': original_image,
'mask_image': mask_image,
'generator': generator,
'num_inference_steps': 2,
'output_type': 'numpy',
}
return inputs
@unittest.skipIf(
torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , )
def __a ( self : List[Any] ):
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )
def __a ( self : Optional[int] ):
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' )
def __a ( self : str ):
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
super().test_save_load_floataa(expected_max_diff=1E-1 )
def __a ( self : List[str] ):
self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 )
def __a ( self : Optional[Any] ):
self._test_save_load_local()
def __a ( self : List[Any] ):
self._test_inference_batch_single_identical(
expected_max_diff=1E-2 , )
| 364 |
import random
import torch
from huggingface_hub import HfApi
from diffusers import UNetaDModel
_lowercase : Dict =HfApi()
_lowercase : str ={}
# fmt: off
_lowercase : Union[str, Any] =torch.tensor([
-0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467,
1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189,
-1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839,
0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557
])
_lowercase : Optional[Any] =torch.tensor([
-2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436,
1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208,
-2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948,
2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365
])
_lowercase : Union[str, Any] =torch.tensor([
-0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869,
-0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304,
-0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925,
0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943
])
_lowercase : Optional[Any] =torch.tensor([
0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172,
-0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309,
0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805,
-0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505
])
_lowercase : Tuple =torch.tensor([
0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133,
-0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395,
0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559,
-0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386
])
_lowercase : int =torch.tensor([
0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078,
-0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330,
0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683,
-0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431
])
_lowercase : Tuple =torch.tensor([
0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042,
-0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398,
0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574,
-0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390
])
_lowercase : Optional[int] =torch.tensor([
0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042,
-0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290,
0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746,
-0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473
])
_lowercase : List[Any] =torch.tensor([
-1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330,
1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243,
-2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810,
1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251])
_lowercase : List[Any] =torch.tensor([
-1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324,
0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181,
-2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259,
1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266
])
_lowercase : int =torch.tensor([
-1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212,
0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027,
-2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131,
1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355
])
_lowercase : List[Any] =torch.tensor([
-2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959,
1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351,
-3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341,
3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066
])
_lowercase : Any =torch.tensor([
-2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740,
1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398,
-2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395,
2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243
])
_lowercase : List[str] =torch.tensor([
-2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336,
1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908,
-3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560,
3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343
])
_lowercase : Tuple =torch.tensor([
-1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344,
1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391,
-2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439,
1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219
])
# fmt: on
_lowercase : Optional[int] =api.list_models(filter="""diffusers""")
for mod in models:
if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256":
_lowercase : str ="""/home/patrick/google_checkpoints/""" + mod.modelId.split("""/""")[-1]
print(F'''Started running {mod.modelId}!!!''')
if mod.modelId.startswith("""CompVis"""):
_lowercase : str =UNetaDModel.from_pretrained(local_checkpoint, subfolder="""unet""")
else:
_lowercase : Dict =UNetaDModel.from_pretrained(local_checkpoint)
torch.manual_seed(0)
random.seed(0)
_lowercase : Optional[Any] =torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
_lowercase : Dict =torch.tensor([10] * noise.shape[0])
with torch.no_grad():
_lowercase : Union[str, Any] =model(noise, time_step).sample
assert torch.allclose(
logits[0, 0, 0, :30], results["""_""".join("""_""".join(mod.modelId.split("""/""")).split("""-"""))], atol=1e-3
)
print(F'''{mod.modelId} has passed successfully!!!''')
| 364 | 1 |
import argparse
from typing import List
import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset
# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
SCREAMING_SNAKE_CASE = 1_6
SCREAMING_SNAKE_CASE = 3_2
def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 16 ):
__a = AutoTokenizer.from_pretrained("""bert-base-cased""" )
__a = DatasetDict(
{
"""train""": dataset["""train"""].select(lowerCAmelCase__ ),
"""validation""": dataset["""train"""].select(lowerCAmelCase__ ),
"""test""": dataset["""validation"""],
} )
def tokenize_function(lowerCAmelCase__ ):
# max_length=None => use the model max length (it's actually the default)
__a = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
__a = datasets.map(
lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
__a = tokenized_datasets.rename_column("""label""" , """labels""" )
def collate_fn(lowerCAmelCase__ ):
# On TPU it's best to pad everything to the same length or training will be very slow.
__a = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
__a = 16
elif accelerator.mixed_precision != "no":
__a = 8
else:
__a = None
return tokenizer.pad(
lowerCAmelCase__ , padding="""longest""" , max_length=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_tensors="""pt""" , )
# Instantiate dataloaders.
__a = DataLoader(
tokenized_datasets["""train"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ )
__a = DataLoader(
tokenized_datasets["""validation"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ )
__a = DataLoader(
tokenized_datasets["""test"""] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ )
return train_dataloader, eval_dataloader, test_dataloader
def a (lowerCAmelCase__ , lowerCAmelCase__ ):
# New Code #
__a = []
# Download the dataset
__a = load_dataset("""glue""" , """mrpc""" )
# Create our splits
__a = StratifiedKFold(n_splits=int(args.num_folds ) )
# Initialize accelerator
__a = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__a = config["""lr"""]
__a = int(config["""num_epochs"""] )
__a = int(config["""seed"""] )
__a = int(config["""batch_size"""] )
__a = evaluate.load("""glue""" , """mrpc""" )
# If the batch size is too big we use gradient accumulation
__a = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
__a = batch_size // MAX_GPU_BATCH_SIZE
__a = MAX_GPU_BATCH_SIZE
set_seed(lowerCAmelCase__ )
# New Code #
# Create our folds:
__a = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] )
__a = []
# Iterate over them
for i, (train_idxs, valid_idxs) in enumerate(lowerCAmelCase__ ):
__a , __a , __a = get_fold_dataloaders(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__a = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=lowerCAmelCase__ )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
__a = model.to(accelerator.device )
# Instantiate optimizer
__a = AdamW(params=model.parameters() , lr=lowerCAmelCase__ )
# Instantiate scheduler
__a = get_linear_schedule_with_warmup(
optimizer=lowerCAmelCase__ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase__ ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
__a , __a , __a , __a , __a = accelerator.prepare(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
# Now we train the model
for epoch in range(lowerCAmelCase__ ):
model.train()
for step, batch in enumerate(lowerCAmelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
__a = model(**lowerCAmelCase__ )
__a = outputs.loss
__a = loss / gradient_accumulation_steps
accelerator.backward(lowerCAmelCase__ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(lowerCAmelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__a = model(**lowerCAmelCase__ )
__a = outputs.logits.argmax(dim=-1 )
__a , __a = accelerator.gather_for_metrics((predictions, batch["""labels"""]) )
metric.add_batch(
predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , )
__a = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f'''epoch {epoch}:''' , lowerCAmelCase__ )
# New Code #
# We also run predictions on the test set at the very end
__a = []
for step, batch in enumerate(lowerCAmelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
__a = model(**lowerCAmelCase__ )
__a = outputs.logits
__a , __a = accelerator.gather_for_metrics((predictions, batch["""labels"""]) )
fold_predictions.append(predictions.cpu() )
if i == 0:
# We need all of the test predictions
test_references.append(references.cpu() )
# Use accelerator.print to print only on the main process.
test_predictions.append(torch.cat(lowerCAmelCase__ , dim=0 ) )
# We now need to release all our memory and get rid of the current model, optimizer, etc
accelerator.free_memory()
# New Code #
# Finally we check the accuracy of our folded results:
__a = torch.cat(lowerCAmelCase__ , dim=0 )
__a = torch.stack(lowerCAmelCase__ , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 )
__a = metric.compute(predictions=lowerCAmelCase__ , references=lowerCAmelCase__ )
accelerator.print("""Average test metrics from all folds:""" , lowerCAmelCase__ )
def a ():
__a = argparse.ArgumentParser(description="""Simple example of training script.""" )
parser.add_argument(
"""--mixed_precision""" , type=lowerCAmelCase__ , default=lowerCAmelCase__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose"""
"""between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
"""and an Nvidia Ampere GPU.""" , )
parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" )
# New Code #
parser.add_argument("""--num_folds""" , type=lowerCAmelCase__ , default=3 , help="""The number of splits to perform across the dataset""" )
__a = parser.parse_args()
__a = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
training_function(lowerCAmelCase__ , lowerCAmelCase__ )
if __name__ == "__main__":
main()
| 712 |
import argparse
import os
import shutil
from pathlib import Path
import onnx
import torch
from packaging import version
from torch.onnx import export
from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline
SCREAMING_SNAKE_CASE = version.parse(version.parse(torch.__version__).base_version) < version.parse('1.11')
def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False , ):
output_path.parent.mkdir(parents=lowerCAmelCase__ , exist_ok=lowerCAmelCase__ )
# PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11,
# so we check the torch version for backwards compatibility
if is_torch_less_than_1_11:
export(
lowerCAmelCase__ , lowerCAmelCase__ , f=output_path.as_posix() , input_names=lowerCAmelCase__ , output_names=lowerCAmelCase__ , dynamic_axes=lowerCAmelCase__ , do_constant_folding=lowerCAmelCase__ , use_external_data_format=lowerCAmelCase__ , enable_onnx_checker=lowerCAmelCase__ , opset_version=lowerCAmelCase__ , )
else:
export(
lowerCAmelCase__ , lowerCAmelCase__ , f=output_path.as_posix() , input_names=lowerCAmelCase__ , output_names=lowerCAmelCase__ , dynamic_axes=lowerCAmelCase__ , do_constant_folding=lowerCAmelCase__ , opset_version=lowerCAmelCase__ , )
@torch.no_grad()
def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = False ):
__a = torch.floataa if fpaa else torch.floataa
if fpaa and torch.cuda.is_available():
__a = """cuda"""
elif fpaa and not torch.cuda.is_available():
raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" )
else:
__a = """cpu"""
__a = StableDiffusionPipeline.from_pretrained(lowerCAmelCase__ , torch_dtype=lowerCAmelCase__ ).to(lowerCAmelCase__ )
__a = Path(lowerCAmelCase__ )
# TEXT ENCODER
__a = pipeline.text_encoder.config.max_position_embeddings
__a = pipeline.text_encoder.config.hidden_size
__a = pipeline.tokenizer(
"""A sample prompt""" , padding="""max_length""" , max_length=pipeline.tokenizer.model_max_length , truncation=lowerCAmelCase__ , return_tensors="""pt""" , )
onnx_export(
pipeline.text_encoder , model_args=(text_input.input_ids.to(device=lowerCAmelCase__ , dtype=torch.intaa )) , output_path=output_path / """text_encoder""" / """model.onnx""" , ordered_input_names=["""input_ids"""] , output_names=["""last_hidden_state""", """pooler_output"""] , dynamic_axes={
"""input_ids""": {0: """batch""", 1: """sequence"""},
} , opset=lowerCAmelCase__ , )
del pipeline.text_encoder
# UNET
__a = pipeline.unet.config.in_channels
__a = pipeline.unet.config.sample_size
__a = output_path / """unet""" / """model.onnx"""
onnx_export(
pipeline.unet , model_args=(
torch.randn(2 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ).to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ),
torch.randn(2 ).to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ),
torch.randn(2 , lowerCAmelCase__ , lowerCAmelCase__ ).to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ),
False,
) , output_path=lowerCAmelCase__ , ordered_input_names=["""sample""", """timestep""", """encoder_hidden_states""", """return_dict"""] , output_names=["""out_sample"""] , dynamic_axes={
"""sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""},
"""timestep""": {0: """batch"""},
"""encoder_hidden_states""": {0: """batch""", 1: """sequence"""},
} , opset=lowerCAmelCase__ , use_external_data_format=lowerCAmelCase__ , )
__a = str(unet_path.absolute().as_posix() )
__a = os.path.dirname(lowerCAmelCase__ )
__a = onnx.load(lowerCAmelCase__ )
# clean up existing tensor files
shutil.rmtree(lowerCAmelCase__ )
os.mkdir(lowerCAmelCase__ )
# collate external tensor files into one
onnx.save_model(
lowerCAmelCase__ , lowerCAmelCase__ , save_as_external_data=lowerCAmelCase__ , all_tensors_to_one_file=lowerCAmelCase__ , location="""weights.pb""" , convert_attribute=lowerCAmelCase__ , )
del pipeline.unet
# VAE ENCODER
__a = pipeline.vae
__a = vae_encoder.config.in_channels
__a = vae_encoder.config.sample_size
# need to get the raw tensor output (sample) from the encoder
__a = lambda lowerCAmelCase__ , lowerCAmelCase__ : vae_encoder.encode(lowerCAmelCase__ , lowerCAmelCase__ )[0].sample()
onnx_export(
lowerCAmelCase__ , model_args=(
torch.randn(1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ).to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ),
False,
) , output_path=output_path / """vae_encoder""" / """model.onnx""" , ordered_input_names=["""sample""", """return_dict"""] , output_names=["""latent_sample"""] , dynamic_axes={
"""sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""},
} , opset=lowerCAmelCase__ , )
# VAE DECODER
__a = pipeline.vae
__a = vae_decoder.config.latent_channels
__a = vae_decoder.config.out_channels
# forward only through the decoder part
__a = vae_encoder.decode
onnx_export(
lowerCAmelCase__ , model_args=(
torch.randn(1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ).to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ),
False,
) , output_path=output_path / """vae_decoder""" / """model.onnx""" , ordered_input_names=["""latent_sample""", """return_dict"""] , output_names=["""sample"""] , dynamic_axes={
"""latent_sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""},
} , opset=lowerCAmelCase__ , )
del pipeline.vae
# SAFETY CHECKER
if pipeline.safety_checker is not None:
__a = pipeline.safety_checker
__a = safety_checker.config.vision_config.num_channels
__a = safety_checker.config.vision_config.image_size
__a = safety_checker.forward_onnx
onnx_export(
pipeline.safety_checker , model_args=(
torch.randn(
1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ).to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ),
torch.randn(1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ).to(device=lowerCAmelCase__ , dtype=lowerCAmelCase__ ),
) , output_path=output_path / """safety_checker""" / """model.onnx""" , ordered_input_names=["""clip_input""", """images"""] , output_names=["""out_images""", """has_nsfw_concepts"""] , dynamic_axes={
"""clip_input""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""},
"""images""": {0: """batch""", 1: """height""", 2: """width""", 3: """channels"""},
} , opset=lowerCAmelCase__ , )
del pipeline.safety_checker
__a = OnnxRuntimeModel.from_pretrained(output_path / """safety_checker""" )
__a = pipeline.feature_extractor
else:
__a = None
__a = None
__a = OnnxStableDiffusionPipeline(
vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / """vae_encoder""" ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / """vae_decoder""" ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / """text_encoder""" ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / """unet""" ) , scheduler=pipeline.scheduler , safety_checker=lowerCAmelCase__ , feature_extractor=lowerCAmelCase__ , requires_safety_checker=safety_checker is not None , )
onnx_pipeline.save_pretrained(lowerCAmelCase__ )
print("""ONNX pipeline saved to""" , lowerCAmelCase__ )
del pipeline
del onnx_pipeline
__a = OnnxStableDiffusionPipeline.from_pretrained(lowerCAmelCase__ , provider="""CPUExecutionProvider""" )
print("""ONNX pipeline is loadable""" )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
parser.add_argument(
'--model_path',
type=str,
required=True,
help='Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).',
)
parser.add_argument('--output_path', type=str, required=True, help='Path to the output model.')
parser.add_argument(
'--opset',
default=1_4,
type=int,
help='The version of the ONNX operator set to use.',
)
parser.add_argument('--fp16', action='store_true', default=False, help='Export the models in `float16` mode')
SCREAMING_SNAKE_CASE = parser.parse_args()
convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
| 209 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_UpperCamelCase = logging.get_logger(__name__)
_UpperCamelCase = {
'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json',
# See all CANINE models at https://huggingface.co/models?filter=canine
}
class lowerCamelCase_ ( __lowerCamelCase ):
"""simple docstring"""
a_ ='canine'
def __init__( self : Optional[Any] , _a : Optional[Any]=768 , _a : Union[str, Any]=12 , _a : Dict=12 , _a : Tuple=3072 , _a : str="gelu" , _a : Optional[int]=0.1 , _a : Optional[int]=0.1 , _a : Dict=1_6384 , _a : Tuple=16 , _a : Any=0.02 , _a : int=1e-12 , _a : Tuple=0 , _a : int=0Xe_000 , _a : Optional[Any]=0Xe_001 , _a : Optional[Any]=4 , _a : int=4 , _a : str=8 , _a : Union[str, Any]=1_6384 , _a : List[Any]=128 , **_a : Optional[int] , ) -> Optional[int]:
super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a )
__lowerCamelCase : Tuple = max_position_embeddings
__lowerCamelCase : Optional[Any] = hidden_size
__lowerCamelCase : Union[str, Any] = num_hidden_layers
__lowerCamelCase : Optional[int] = num_attention_heads
__lowerCamelCase : Union[str, Any] = intermediate_size
__lowerCamelCase : Tuple = hidden_act
__lowerCamelCase : str = hidden_dropout_prob
__lowerCamelCase : Union[str, Any] = attention_probs_dropout_prob
__lowerCamelCase : List[Any] = initializer_range
__lowerCamelCase : Tuple = type_vocab_size
__lowerCamelCase : List[str] = layer_norm_eps
# Character config:
__lowerCamelCase : List[Any] = downsampling_rate
__lowerCamelCase : Optional[Any] = upsampling_kernel_size
__lowerCamelCase : Any = num_hash_functions
__lowerCamelCase : Optional[int] = num_hash_buckets
__lowerCamelCase : Tuple = local_transformer_stride
| 459 |
import warnings
from contextlib import contextmanager
from ....processing_utils import ProcessorMixin
class lowerCamelCase ( __lowerCamelCase ):
UpperCamelCase_ : Optional[Any] = 'MCTCTFeatureExtractor'
UpperCamelCase_ : List[Any] = 'AutoTokenizer'
def __init__( self :Tuple , lowercase :List[str] , lowercase :Dict ) -> Tuple:
"""simple docstring"""
super().__init__(lowercase , lowercase )
SCREAMING_SNAKE_CASE = self.feature_extractor
SCREAMING_SNAKE_CASE = False
def __call__( self :Union[str, Any] , *lowercase :Union[str, Any] , **lowercase :str ) -> int:
"""simple docstring"""
if self._in_target_context_manager:
return self.current_processor(*lowercase , **lowercase )
if "raw_speech" in kwargs:
warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''' )
SCREAMING_SNAKE_CASE = kwargs.pop('''raw_speech''' )
else:
SCREAMING_SNAKE_CASE = kwargs.pop('''audio''' , lowercase )
SCREAMING_SNAKE_CASE = kwargs.pop('''sampling_rate''' , lowercase )
SCREAMING_SNAKE_CASE = kwargs.pop('''text''' , lowercase )
if len(lowercase ) > 0:
SCREAMING_SNAKE_CASE = args[0]
SCREAMING_SNAKE_CASE = args[1:]
if audio is None and text is None:
raise ValueError('''You need to specify either an `audio` or `text` input to process.''' )
if audio is not None:
SCREAMING_SNAKE_CASE = self.feature_extractor(lowercase , *lowercase , sampling_rate=lowercase , **lowercase )
if text is not None:
SCREAMING_SNAKE_CASE = self.tokenizer(lowercase , **lowercase )
if text is None:
return inputs
elif audio is None:
return encodings
else:
SCREAMING_SNAKE_CASE = encodings['''input_ids''']
return inputs
def snake_case__ ( self :Dict , *lowercase :Union[str, Any] , **lowercase :List[str] ) -> Union[str, Any]:
"""simple docstring"""
return self.tokenizer.batch_decode(*lowercase , **lowercase )
def snake_case__ ( self :List[Any] , *lowercase :List[Any] , **lowercase :List[str] ) -> int:
"""simple docstring"""
if self._in_target_context_manager:
return self.current_processor.pad(*lowercase , **lowercase )
SCREAMING_SNAKE_CASE = kwargs.pop('''input_features''' , lowercase )
SCREAMING_SNAKE_CASE = kwargs.pop('''labels''' , lowercase )
if len(lowercase ) > 0:
SCREAMING_SNAKE_CASE = args[0]
SCREAMING_SNAKE_CASE = args[1:]
if input_features is not None:
SCREAMING_SNAKE_CASE = self.feature_extractor.pad(lowercase , *lowercase , **lowercase )
if labels is not None:
SCREAMING_SNAKE_CASE = self.tokenizer.pad(lowercase , **lowercase )
if labels is None:
return input_features
elif input_features is None:
return labels
else:
SCREAMING_SNAKE_CASE = labels['''input_ids''']
return input_features
def snake_case__ ( self :Dict , *lowercase :List[str] , **lowercase :Union[str, Any] ) -> List[Any]:
"""simple docstring"""
return self.tokenizer.decode(*lowercase , **lowercase )
@contextmanager
def snake_case__ ( self :str ) -> Union[str, Any]:
"""simple docstring"""
warnings.warn(
'''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
'''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
'''your audio inputs, or in a separate call.''' )
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = self.tokenizer
yield
SCREAMING_SNAKE_CASE = self.feature_extractor
SCREAMING_SNAKE_CASE = False | 201 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
SCREAMING_SNAKE_CASE = {
'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE = [
'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
'MegaForCausalLM',
'MegaForMaskedLM',
'MegaForMultipleChoice',
'MegaForQuestionAnswering',
'MegaForSequenceClassification',
'MegaForTokenClassification',
'MegaModel',
'MegaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 209 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
enable_full_determinism,
load_numpy,
nightly,
require_torch_gpu,
slow,
torch_device,
)
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class __UpperCAmelCase ( __A , unittest.TestCase ):
"""simple docstring"""
_lowerCamelCase = LDMTextToImagePipeline
_lowerCamelCase = TEXT_TO_IMAGE_PARAMS - {
"""negative_prompt""",
"""negative_prompt_embeds""",
"""cross_attention_kwargs""",
"""prompt_embeds""",
}
_lowerCamelCase = PipelineTesterMixin.required_optional_params - {
"""num_images_per_prompt""",
"""callback""",
"""callback_steps""",
}
_lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS
_lowerCamelCase = False
def snake_case_ ( self ):
torch.manual_seed(0 )
__a = 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 , )
__a = DDIMScheduler(
beta_start=0.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__A , set_alpha_to_one=__A , )
torch.manual_seed(0 )
__a = 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 )
__a = 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 , )
__a = CLIPTextModel(__A )
__a = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
__a = {
"""unet""": unet,
"""scheduler""": scheduler,
"""vqvae""": vae,
"""bert""": text_encoder,
"""tokenizer""": tokenizer,
}
return components
def snake_case_ ( self , __A , __A=0 ):
if str(__A ).startswith("""mps""" ):
__a = torch.manual_seed(__A )
else:
__a = torch.Generator(device=__A ).manual_seed(__A )
__a = {
"""prompt""": """A painting of a squirrel eating a burger""",
"""generator""": generator,
"""num_inference_steps""": 2,
"""guidance_scale""": 6.0,
"""output_type""": """numpy""",
}
return inputs
def snake_case_ ( self ):
__a = """cpu""" # ensure determinism for the device-dependent torch.Generator
__a = self.get_dummy_components()
__a = LDMTextToImagePipeline(**__A )
pipe.to(__A )
pipe.set_progress_bar_config(disable=__A )
__a = self.get_dummy_inputs(__A )
__a = pipe(**__A ).images
__a = image[0, -3:, -3:, -1]
assert image.shape == (1, 16, 16, 3)
__a = np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
@slow
@require_torch_gpu
class __UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def snake_case_ ( self ):
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def snake_case_ ( self , __A , __A=torch.floataa , __A=0 ):
__a = torch.manual_seed(__A )
__a = np.random.RandomState(__A ).standard_normal((1, 4, 32, 32) )
__a = torch.from_numpy(__A ).to(device=__A , dtype=__A )
__a = {
"""prompt""": """A painting of a squirrel eating a burger""",
"""latents""": latents,
"""generator""": generator,
"""num_inference_steps""": 3,
"""guidance_scale""": 6.0,
"""output_type""": """numpy""",
}
return inputs
def snake_case_ ( self ):
__a = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__A )
pipe.set_progress_bar_config(disable=__A )
__a = self.get_inputs(__A )
__a = pipe(**__A ).images
__a = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 256, 256, 3)
__a = np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878] )
__a = np.abs(expected_slice - image_slice ).max()
assert max_diff < 1E-3
@nightly
@require_torch_gpu
class __UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def snake_case_ ( self ):
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def snake_case_ ( self , __A , __A=torch.floataa , __A=0 ):
__a = torch.manual_seed(__A )
__a = np.random.RandomState(__A ).standard_normal((1, 4, 32, 32) )
__a = torch.from_numpy(__A ).to(device=__A , dtype=__A )
__a = {
"""prompt""": """A painting of a squirrel eating a burger""",
"""latents""": latents,
"""generator""": generator,
"""num_inference_steps""": 50,
"""guidance_scale""": 6.0,
"""output_type""": """numpy""",
}
return inputs
def snake_case_ ( self ):
__a = LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(__A )
pipe.set_progress_bar_config(disable=__A )
__a = self.get_inputs(__A )
__a = pipe(**__A ).images[0]
__a = load_numpy(
"""https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy""" )
__a = np.abs(expected_image - image ).max()
assert max_diff < 1E-3
| 209 | 1 |
'''simple docstring'''
from .integrations import (
is_optuna_available,
is_ray_available,
is_sigopt_available,
is_wandb_available,
run_hp_search_optuna,
run_hp_search_ray,
run_hp_search_sigopt,
run_hp_search_wandb,
)
from .trainer_utils import (
HPSearchBackend,
default_hp_space_optuna,
default_hp_space_ray,
default_hp_space_sigopt,
default_hp_space_wandb,
)
from .utils import logging
__lowerCAmelCase : Dict = logging.get_logger(__name__)
class A :
a_ = 42
a_ = None
@staticmethod
def snake_case__ ( ) -> Optional[Any]:
raise NotImplementedError
def snake_case__ ( self : Optional[Any] , __a : List[Any] , __a : int , __a : str , **__a : Optional[Any] ) -> List[str]:
raise NotImplementedError
def snake_case__ ( self : str , __a : Optional[int] ) -> Optional[int]:
raise NotImplementedError
def snake_case__ ( self : Optional[Any] ) -> List[str]:
if not self.is_available():
raise RuntimeError(
f"""You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.""" )
@classmethod
def snake_case__ ( cls : List[Any] ) -> Optional[Any]:
return f"""`pip install {cls.pip_package or cls.name}`"""
class A ( UpperCAmelCase ):
a_ = '''optuna'''
@staticmethod
def snake_case__ ( ) -> Optional[Any]:
return is_optuna_available()
def snake_case__ ( self : Union[str, Any] , __a : int , __a : int , __a : str , **__a : Optional[int] ) -> Optional[int]:
return run_hp_search_optuna(__a , __a , __a , **__a )
def snake_case__ ( self : int , __a : str ) -> str:
return default_hp_space_optuna(__a )
class A ( UpperCAmelCase ):
a_ = '''ray'''
a_ = '''\'ray[tune]\''''
@staticmethod
def snake_case__ ( ) -> Tuple:
return is_ray_available()
def snake_case__ ( self : Tuple , __a : List[Any] , __a : int , __a : str , **__a : str ) -> Dict:
return run_hp_search_ray(__a , __a , __a , **__a )
def snake_case__ ( self : Union[str, Any] , __a : Optional[int] ) -> Tuple:
return default_hp_space_ray(__a )
class A ( UpperCAmelCase ):
a_ = '''sigopt'''
@staticmethod
def snake_case__ ( ) -> Dict:
return is_sigopt_available()
def snake_case__ ( self : Optional[int] , __a : Tuple , __a : int , __a : str , **__a : List[Any] ) -> List[Any]:
return run_hp_search_sigopt(__a , __a , __a , **__a )
def snake_case__ ( self : Tuple , __a : Any ) -> List[Any]:
return default_hp_space_sigopt(__a )
class A ( UpperCAmelCase ):
a_ = '''wandb'''
@staticmethod
def snake_case__ ( ) -> str:
return is_wandb_available()
def snake_case__ ( self : List[str] , __a : Union[str, Any] , __a : int , __a : str , **__a : Union[str, Any] ) -> Union[str, Any]:
return run_hp_search_wandb(__a , __a , __a , **__a )
def snake_case__ ( self : Dict , __a : Any ) -> Tuple:
return default_hp_space_wandb(__a )
__lowerCAmelCase : List[str] = {
HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}
def lowerCAmelCase ( ):
"""simple docstring"""
__UpperCAmelCase = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
if len(UpperCamelCase__ ) > 0:
__UpperCAmelCase = available_backends[0].name
if len(UpperCamelCase__ ) > 1:
logger.info(
f"""{len(UpperCamelCase__ )} hyperparameter search backends available. Using {name} as the default.""" )
return name
raise RuntimeError(
'''No hyperparameter search backend available.\n'''
+ '''\n'''.join(
f""" - To install {backend.name} run {backend.pip_install()}"""
for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
| 262 | '''simple docstring'''
import argparse
import torch
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCAmelCase ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] ):
"""simple docstring"""
# Initialise PyTorch model
__UpperCAmelCase = BertConfig.from_json_file(UpperCamelCase__ )
print(f"""Building PyTorch model from configuration: {config}""" )
__UpperCAmelCase = BertForPreTraining(UpperCamelCase__ )
# Load weights from tf checkpoint
load_tf_weights_in_bert(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# Save pytorch-model
print(f"""Save PyTorch model to {pytorch_dump_path}""" )
torch.save(model.state_dict() , UpperCamelCase__ )
if __name__ == "__main__":
__lowerCAmelCase : Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--bert_config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained BERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
__lowerCAmelCase : Optional[Any] = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 262 | 1 |
import fire
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer
from utils import SeqaSeqDataset, pickle_save
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=10_24 , _lowerCAmelCase=10_24 , _lowerCAmelCase=False , **_lowerCAmelCase ):
"""simple docstring"""
UpperCAmelCase = AutoTokenizer.from_pretrained(_lowerCAmelCase )
UpperCAmelCase = SeqaSeqDataset(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , type_path="train" , **_lowerCAmelCase )
UpperCAmelCase = tok.pad_token_id
def get_lens(_lowerCAmelCase ):
UpperCAmelCase = tqdm(
DataLoader(_lowerCAmelCase , batch_size=5_12 , num_workers=8 , shuffle=_lowerCAmelCase , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , )
UpperCAmelCase = []
for batch in dl:
UpperCAmelCase = batch["input_ids"].ne(_lowerCAmelCase ).sum(1 ).tolist()
UpperCAmelCase = batch["labels"].ne(_lowerCAmelCase ).sum(1 ).tolist()
if consider_target:
for src, tgt in zip(_lowerCAmelCase , _lowerCAmelCase ):
max_lens.append(max(_lowerCAmelCase , _lowerCAmelCase ) )
else:
max_lens.extend(_lowerCAmelCase )
return max_lens
UpperCAmelCase = get_lens(_lowerCAmelCase )
UpperCAmelCase = SeqaSeqDataset(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , type_path="val" , **_lowerCAmelCase )
UpperCAmelCase = get_lens(_lowerCAmelCase )
pickle_save(_lowerCAmelCase , train_ds.len_file )
pickle_save(_lowerCAmelCase , val_ds.len_file )
if __name__ == "__main__":
fire.Fire(save_len_file)
| 405 |
class __magic_name__ ( _a):
pass
class __magic_name__ ( _a):
pass
class __magic_name__ :
def __init__( self : Optional[int] ):
UpperCAmelCase = [
[],
[],
[],
]
def _UpperCAmelCase ( self : Tuple ,__SCREAMING_SNAKE_CASE : int ,__SCREAMING_SNAKE_CASE : int ):
try:
if len(self.queues[priority] ) >= 1_0_0:
raise OverflowError("Maximum queue size is 100" )
self.queues[priority].append(__SCREAMING_SNAKE_CASE )
except IndexError:
raise ValueError("Valid priorities are 0, 1, and 2" )
def _UpperCAmelCase ( self : List[str] ):
for queue in self.queues:
if queue:
return queue.pop(0 )
raise UnderFlowError("All queues are empty" )
def __str__( self : Optional[Any] ):
return "\n".join(f'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) )
class __magic_name__ :
def __init__( self : Any ):
UpperCAmelCase = []
def _UpperCAmelCase ( self : List[str] ,__SCREAMING_SNAKE_CASE : int ):
if len(self.queue ) == 1_0_0:
raise OverFlowError("Maximum queue size is 100" )
self.queue.append(__SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( self : Optional[Any] ):
if not self.queue:
raise UnderFlowError("The queue is empty" )
else:
UpperCAmelCase = min(self.queue )
self.queue.remove(__SCREAMING_SNAKE_CASE )
return data
def __str__( self : Optional[Any] ):
return str(self.queue )
def __UpperCamelCase ( ):
"""simple docstring"""
UpperCAmelCase = FixedPriorityQueue()
fpq.enqueue(0 , 10 )
fpq.enqueue(1 , 70 )
fpq.enqueue(0 , 1_00 )
fpq.enqueue(2 , 1 )
fpq.enqueue(2 , 5 )
fpq.enqueue(1 , 7 )
fpq.enqueue(2 , 4 )
fpq.enqueue(1 , 64 )
fpq.enqueue(0 , 1_28 )
print(_lowerCAmelCase )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(_lowerCAmelCase )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
print(fpq.dequeue() )
def __UpperCamelCase ( ):
"""simple docstring"""
UpperCAmelCase = ElementPriorityQueue()
epq.enqueue(10 )
epq.enqueue(70 )
epq.enqueue(1_00 )
epq.enqueue(1 )
epq.enqueue(5 )
epq.enqueue(7 )
epq.enqueue(4 )
epq.enqueue(64 )
epq.enqueue(1_28 )
print(_lowerCAmelCase )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(_lowerCAmelCase )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
print(epq.dequeue() )
if __name__ == "__main__":
fixed_priority_queue()
element_priority_queue()
| 405 | 1 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a_ = logging.get_logger(__name__)
a_ = {
'microsoft/swinv2-tiny-patch4-window8-256': (
'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json'
),
}
class UpperCAmelCase_ ( snake_case ):
UpperCamelCase ="swinv2"
UpperCamelCase ={
"num_attention_heads": "num_heads",
"num_hidden_layers": "num_layers",
}
def __init__( self , UpperCamelCase_=2_24 , UpperCamelCase_=4 , UpperCamelCase_=3 , UpperCamelCase_=96 , UpperCamelCase_=[2, 2, 6, 2] , UpperCamelCase_=[3, 6, 12, 24] , UpperCamelCase_=7 , UpperCamelCase_=4.0 , UpperCamelCase_=True , UpperCamelCase_=0.0 , UpperCamelCase_=0.0 , UpperCamelCase_=0.1 , UpperCamelCase_="gelu" , UpperCamelCase_=False , UpperCamelCase_=0.0_2 , UpperCamelCase_=1E-5 , UpperCamelCase_=32 , **UpperCamelCase_ , ) -> List[Any]:
super().__init__(**UpperCamelCase_ )
__lowercase : Union[str, Any] = image_size
__lowercase : Optional[int] = patch_size
__lowercase : int = num_channels
__lowercase : List[str] = embed_dim
__lowercase : List[Any] = depths
__lowercase : List[str] = len(UpperCamelCase_ )
__lowercase : List[Any] = num_heads
__lowercase : Optional[int] = window_size
__lowercase : int = mlp_ratio
__lowercase : Any = qkv_bias
__lowercase : Optional[int] = hidden_dropout_prob
__lowercase : Tuple = attention_probs_dropout_prob
__lowercase : Optional[int] = drop_path_rate
__lowercase : Tuple = hidden_act
__lowercase : Tuple = use_absolute_embeddings
__lowercase : Dict = layer_norm_eps
__lowercase : Dict = initializer_range
__lowercase : Optional[Any] = encoder_stride
# we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
__lowercase : Optional[int] = int(embed_dim * 2 ** (len(UpperCamelCase_ ) - 1) )
__lowercase : Union[str, Any] = (0, 0, 0, 0)
| 76 |
import math
def A ( lowercase__ : Tuple , lowercase__ : Union[str, Any] ) -> Optional[Any]:
if 0 not in (x, y):
# We use the relation x^y = y*log10(x), where 10 is the base.
return y * math.logaa(lowercase__ )
else:
if x == 0: # 0 raised to any number is 0
return 0
elif y == 0:
return 1 # any number raised to 0 is 1
raise AssertionError("""This should never happen""" )
if __name__ == "__main__": # Main function
# Read two numbers from input and typecast them to int using map function.
# Here x is the base and y is the power.
UpperCamelCase = "Enter the base and the power separated by a comma: "
UpperCamelCase , UpperCamelCase = map(int, input(prompt).split(","))
UpperCamelCase , UpperCamelCase = map(int, input(prompt).split(","))
# We find the log of each number, using the function res(), which takes two
# arguments.
UpperCamelCase = res(xa, ya)
UpperCamelCase = res(xa, ya)
# We check for the largest number
if resa > resa:
print("Largest number is", xa, "^", ya)
elif resa > resa:
print("Largest number is", xa, "^", ya)
else:
print("Both are equal") | 45 | 0 |
"""simple docstring"""
def snake_case ( lowerCAmelCase_ ) -> None:
_snake_case = generate_pascal_triangle(lowerCAmelCase_ )
for row_idx in range(lowerCAmelCase_ ):
# Print left spaces
for _ in range(num_rows - row_idx - 1 ):
print(end=''' ''' )
# Print row values
for col_idx in range(row_idx + 1 ):
if col_idx != row_idx:
print(triangle[row_idx][col_idx] , end=''' ''' )
else:
print(triangle[row_idx][col_idx] , end='''''' )
print()
def snake_case ( lowerCAmelCase_ ) -> list[list[int]]:
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise TypeError('''The input value of \'num_rows\' should be \'int\'''' )
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
'''The input value of \'num_rows\' should be greater than or equal to 0''' )
_snake_case = []
for current_row_idx in range(lowerCAmelCase_ ):
_snake_case = populate_current_row(lowerCAmelCase_ , lowerCAmelCase_ )
triangle.append(lowerCAmelCase_ )
return triangle
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[int]:
_snake_case = [-1] * (current_row_idx + 1)
# first and last elements of current row are equal to 1
_snake_case , _snake_case = 1, 1
for current_col_idx in range(1 , lowerCAmelCase_ ):
calculate_current_element(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
return current_row
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) -> None:
_snake_case = triangle[current_row_idx - 1][current_col_idx - 1]
_snake_case = triangle[current_row_idx - 1][current_col_idx]
_snake_case = above_to_left_elt + above_to_right_elt
def snake_case ( lowerCAmelCase_ ) -> list[list[int]]:
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise TypeError('''The input value of \'num_rows\' should be \'int\'''' )
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
'''The input value of \'num_rows\' should be greater than or equal to 0''' )
_snake_case = [[1]]
for row_index in range(1 , lowerCAmelCase_ ):
_snake_case = [0] + result[-1] + [0]
_snake_case = row_index + 1
# Calculate the number of distinct elements in a row
_snake_case = sum(divmod(lowerCAmelCase_ , 2 ) )
_snake_case = [
temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 )
]
_snake_case = row_first_half[: (row_index + 1) // 2]
row_second_half.reverse()
_snake_case = row_first_half + row_second_half
result.append(lowerCAmelCase_ )
return result
def snake_case ( ) -> None:
from collections.abc import Callable
from timeit import timeit
def benchmark_a_function(lowerCAmelCase_ , lowerCAmelCase_ ) -> None:
_snake_case = f"""{func.__name__}({value})"""
_snake_case = timeit(f"""__main__.{call}""" , setup='''import __main__''' )
# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
print(f"""{call:38} -- {timing:.4f} seconds""" )
for value in range(15 ): # (1, 7, 14):
for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
benchmark_a_function(lowerCAmelCase_ , lowerCAmelCase_ )
print()
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 404 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
snake_case = {
'''configuration_luke''': ['''LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LukeConfig'''],
'''tokenization_luke''': ['''LukeTokenizer'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case = [
'''LUKE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''LukeForEntityClassification''',
'''LukeForEntityPairClassification''',
'''LukeForEntitySpanClassification''',
'''LukeForMultipleChoice''',
'''LukeForQuestionAnswering''',
'''LukeForSequenceClassification''',
'''LukeForTokenClassification''',
'''LukeForMaskedLM''',
'''LukeModel''',
'''LukePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig
from .tokenization_luke import LukeTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_luke import (
LUKE_PRETRAINED_MODEL_ARCHIVE_LIST,
LukeForEntityClassification,
LukeForEntityPairClassification,
LukeForEntitySpanClassification,
LukeForMaskedLM,
LukeForMultipleChoice,
LukeForQuestionAnswering,
LukeForSequenceClassification,
LukeForTokenClassification,
LukeModel,
LukePreTrainedModel,
)
else:
import sys
snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 404 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
SCREAMING_SNAKE_CASE__ : str = {
"configuration_squeezebert": [
"SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"SqueezeBertConfig",
"SqueezeBertOnnxConfig",
],
"tokenization_squeezebert": ["SqueezeBertTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__ : List[Any] = ["SqueezeBertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__ : Optional[Any] = [
"SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"SqueezeBertForMaskedLM",
"SqueezeBertForMultipleChoice",
"SqueezeBertForQuestionAnswering",
"SqueezeBertForSequenceClassification",
"SqueezeBertForTokenClassification",
"SqueezeBertModel",
"SqueezeBertModule",
"SqueezeBertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_squeezebert import (
SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
SqueezeBertConfig,
SqueezeBertOnnxConfig,
)
from .tokenization_squeezebert import SqueezeBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_squeezebert import (
SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
SqueezeBertForMaskedLM,
SqueezeBertForMultipleChoice,
SqueezeBertForQuestionAnswering,
SqueezeBertForSequenceClassification,
SqueezeBertForTokenClassification,
SqueezeBertModel,
SqueezeBertModule,
SqueezeBertPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 85 |
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class _snake_case ( UpperCAmelCase_ ):
__lowerCAmelCase : Any = ['image_processor', 'tokenizer']
__lowerCAmelCase : Union[str, Any] = 'AutoImageProcessor'
__lowerCAmelCase : int = 'AutoTokenizer'
def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_):
'''simple docstring'''
super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_)
lowercase__ : Union[str, Any] = self.image_processor
def __call__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
if text is None and images is None:
raise ValueError("""You have to specify either text or images. Both cannot be none.""")
if text is not None:
lowercase__ : List[str] = self.tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_)
if images is not None:
lowercase__ : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_)
if text is not None and images is not None:
lowercase__ : Union[str, Any] = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE_) , tensor_type=SCREAMING_SNAKE_CASE_)
def lowercase__ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_)
def lowercase__ ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_):
'''simple docstring'''
return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_)
@property
def lowercase__ ( self):
'''simple docstring'''
return ["input_ids", "attention_mask", "pixel_values"]
| 12 | 0 |
import inspect
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel, VQModel
from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class SCREAMING_SNAKE_CASE_ ( _a ):
"""simple docstring"""
def __init__( self :Optional[int], snake_case :VQModel, snake_case :UNetaDModel, snake_case :DDIMScheduler):
"""simple docstring"""
super().__init__()
self.register_modules(vqvae=snake_case, unet=snake_case, scheduler=snake_case)
@torch.no_grad()
def __call__( self :Tuple, snake_case :int = 1, snake_case :Optional[Union[torch.Generator, List[torch.Generator]]] = None, snake_case :float = 0.0, snake_case :int = 50, snake_case :Optional[str] = "pil", snake_case :bool = True, **snake_case :Any, ):
"""simple docstring"""
_lowercase =randn_tensor(
(batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size), generator=snake_case, )
_lowercase =latents.to(self.device)
# scale the initial noise by the standard deviation required by the scheduler
_lowercase =latents * self.scheduler.init_noise_sigma
self.scheduler.set_timesteps(snake_case)
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
_lowercase ='eta' in set(inspect.signature(self.scheduler.step).parameters.keys())
_lowercase ={}
if accepts_eta:
_lowercase =eta
for t in self.progress_bar(self.scheduler.timesteps):
_lowercase =self.scheduler.scale_model_input(snake_case, snake_case)
# predict the noise residual
_lowercase =self.unet(snake_case, snake_case).sample
# compute the previous noisy sample x_t -> x_t-1
_lowercase =self.scheduler.step(snake_case, snake_case, snake_case, **snake_case).prev_sample
# decode the image latents with the VAE
_lowercase =self.vqvae.decode(snake_case).sample
_lowercase =(image / 2 + 0.5).clamp(0, 1)
_lowercase =image.cpu().permute(0, 2, 3, 1).numpy()
if output_type == "pil":
_lowercase =self.numpy_to_pil(snake_case)
if not return_dict:
return (image,)
return ImagePipelineOutput(images=snake_case)
| 557 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
_SCREAMING_SNAKE_CASE = {
"uclanlp/visualbert-vqa": "https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json",
"uclanlp/visualbert-vqa-pre": "https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json",
"uclanlp/visualbert-vqa-coco-pre": (
"https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json"
),
"uclanlp/visualbert-vcr": "https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json",
"uclanlp/visualbert-vcr-pre": "https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json",
"uclanlp/visualbert-vcr-coco-pre": (
"https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json"
),
"uclanlp/visualbert-nlvr2": "https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json",
"uclanlp/visualbert-nlvr2-pre": "https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json",
"uclanlp/visualbert-nlvr2-coco-pre": (
"https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json"
)
# See all VisualBERT models at https://huggingface.co/models?filter=visual_bert
}
class SCREAMING_SNAKE_CASE_ ( _a ):
"""simple docstring"""
__lowerCAmelCase : Tuple ='''visual_bert'''
def __init__( self :Any, snake_case :Dict=3_0522, snake_case :Optional[Any]=768, snake_case :Optional[Any]=512, snake_case :Tuple=12, snake_case :List[Any]=12, snake_case :List[Any]=3072, snake_case :Optional[int]="gelu", snake_case :Union[str, Any]=0.1, snake_case :List[str]=0.1, snake_case :Optional[Any]=512, snake_case :Tuple=2, snake_case :Optional[int]=0.0_2, snake_case :Union[str, Any]=1e-1_2, snake_case :Union[str, Any]=False, snake_case :Optional[Any]=True, snake_case :Tuple=1, snake_case :int=0, snake_case :Any=2, **snake_case :Union[str, Any], ):
"""simple docstring"""
super().__init__(pad_token_id=snake_case, bos_token_id=snake_case, eos_token_id=snake_case, **snake_case)
_lowercase =vocab_size
_lowercase =max_position_embeddings
_lowercase =hidden_size
_lowercase =visual_embedding_dim
_lowercase =num_hidden_layers
_lowercase =num_attention_heads
_lowercase =intermediate_size
_lowercase =hidden_act
_lowercase =hidden_dropout_prob
_lowercase =attention_probs_dropout_prob
_lowercase =initializer_range
_lowercase =type_vocab_size
_lowercase =layer_norm_eps
_lowercase =bypass_transformer
_lowercase =special_visual_initialize
| 557 | 1 |
"""simple docstring"""
import tempfile
import torch
from diffusers import (
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
UniPCMultistepScheduler,
)
from .test_schedulers import SchedulerCommonTest
class lowerCamelCase__ ( UpperCamelCase_ ):
__UpperCAmelCase = (DPMSolverSinglestepScheduler,)
__UpperCAmelCase = (("""num_inference_steps""", 25),)
def _UpperCAmelCase ( self , **snake_case ) -> str:
"""simple docstring"""
lowercase : Any = {
'''num_train_timesteps''': 1_0_0_0,
'''beta_start''': 0.00_01,
'''beta_end''': 0.02,
'''beta_schedule''': '''linear''',
'''solver_order''': 2,
'''prediction_type''': '''epsilon''',
'''thresholding''': False,
'''sample_max_value''': 1.0,
'''algorithm_type''': '''dpmsolver++''',
'''solver_type''': '''midpoint''',
'''lambda_min_clipped''': -float("""inf""" ),
'''variance_type''': None,
}
config.update(**snake_case )
return config
def _UpperCAmelCase ( self , snake_case=0 , **snake_case ) -> Any:
"""simple docstring"""
lowercase : Union[str, Any] = dict(self.forward_default_kwargs )
lowercase : Tuple = kwargs.pop("""num_inference_steps""" , snake_case )
lowercase : Tuple = self.dummy_sample
lowercase : List[Any] = 0.1 * sample
lowercase : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
lowercase : str = self.get_scheduler_config(**snake_case )
lowercase : Dict = scheduler_class(**snake_case )
scheduler.set_timesteps(snake_case )
# copy over dummy past residuals
lowercase : Tuple = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(snake_case )
lowercase : List[str] = scheduler_class.from_pretrained(snake_case )
new_scheduler.set_timesteps(snake_case )
# copy over dummy past residuals
lowercase : int = dummy_past_residuals[: new_scheduler.config.solver_order]
lowercase : Dict = sample, sample
for t in range(snake_case , time_step + scheduler.config.solver_order + 1 ):
lowercase : str = scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample
lowercase : str = new_scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical"
def _UpperCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
pass
def _UpperCAmelCase ( self , snake_case=0 , **snake_case ) -> Dict:
"""simple docstring"""
lowercase : Optional[int] = dict(self.forward_default_kwargs )
lowercase : List[Any] = kwargs.pop("""num_inference_steps""" , snake_case )
lowercase : Tuple = self.dummy_sample
lowercase : Dict = 0.1 * sample
lowercase : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
lowercase : Optional[Any] = self.get_scheduler_config()
lowercase : Tuple = scheduler_class(**snake_case )
scheduler.set_timesteps(snake_case )
# copy over dummy past residuals (must be after setting timesteps)
lowercase : Tuple = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(snake_case )
lowercase : List[Any] = scheduler_class.from_pretrained(snake_case )
# copy over dummy past residuals
new_scheduler.set_timesteps(snake_case )
# copy over dummy past residual (must be after setting timesteps)
lowercase : Union[str, Any] = dummy_past_residuals[: new_scheduler.config.solver_order]
lowercase : Dict = scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample
lowercase : str = new_scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical"
def _UpperCAmelCase ( self , snake_case=None , **snake_case ) -> List[Any]:
"""simple docstring"""
if scheduler is None:
lowercase : Dict = self.scheduler_classes[0]
lowercase : Dict = self.get_scheduler_config(**snake_case )
lowercase : List[str] = scheduler_class(**snake_case )
lowercase : str = self.scheduler_classes[0]
lowercase : Tuple = self.get_scheduler_config(**snake_case )
lowercase : Optional[Any] = scheduler_class(**snake_case )
lowercase : Tuple = 1_0
lowercase : Optional[Any] = self.dummy_model()
lowercase : List[Any] = self.dummy_sample_deter
scheduler.set_timesteps(snake_case )
for i, t in enumerate(scheduler.timesteps ):
lowercase : str = model(snake_case , snake_case )
lowercase : Tuple = scheduler.step(snake_case , snake_case , snake_case ).prev_sample
return sample
def _UpperCAmelCase ( self ) -> List[str]:
"""simple docstring"""
lowercase : Union[str, Any] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
lowercase : Tuple = 5_0
lowercase : List[Any] = self.dummy_model()
lowercase : List[str] = self.dummy_sample_deter
scheduler.set_timesteps(snake_case )
# make sure that the first t is uneven
for i, t in enumerate(scheduler.timesteps[3:] ):
lowercase : Dict = model(snake_case , snake_case )
lowercase : str = scheduler.step(snake_case , snake_case , snake_case ).prev_sample
lowercase : Union[str, Any] = torch.mean(torch.abs(snake_case ) )
assert abs(result_mean.item() - 0.25_74 ) < 1E-3
def _UpperCAmelCase ( self ) -> str:
"""simple docstring"""
for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
self.check_over_configs(num_train_timesteps=snake_case )
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
# make sure that iterating over schedulers with same config names gives same results
# for defaults
lowercase : Optional[int] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
lowercase : int = self.full_loop(scheduler=snake_case )
lowercase : Optional[int] = torch.mean(torch.abs(snake_case ) )
assert abs(result_mean.item() - 0.27_91 ) < 1E-3
lowercase : Tuple = DEISMultistepScheduler.from_config(scheduler.config )
lowercase : str = DPMSolverMultistepScheduler.from_config(scheduler.config )
lowercase : Dict = UniPCMultistepScheduler.from_config(scheduler.config )
lowercase : Union[str, Any] = DPMSolverSinglestepScheduler.from_config(scheduler.config )
lowercase : List[Any] = self.full_loop(scheduler=snake_case )
lowercase : int = torch.mean(torch.abs(snake_case ) )
assert abs(result_mean.item() - 0.27_91 ) < 1E-3
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
self.check_over_configs(thresholding=snake_case )
for order in [1, 2, 3]:
for solver_type in ["midpoint", "heun"]:
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
thresholding=snake_case , prediction_type=snake_case , sample_max_value=snake_case , algorithm_type="""dpmsolver++""" , solver_order=snake_case , solver_type=snake_case , )
def _UpperCAmelCase ( self ) -> Any:
"""simple docstring"""
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=snake_case )
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
for algorithm_type in ["dpmsolver", "dpmsolver++"]:
for solver_type in ["midpoint", "heun"]:
for order in [1, 2, 3]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
solver_order=snake_case , solver_type=snake_case , prediction_type=snake_case , algorithm_type=snake_case , )
lowercase : int = self.full_loop(
solver_order=snake_case , solver_type=snake_case , prediction_type=snake_case , algorithm_type=snake_case , )
assert not torch.isnan(snake_case ).any(), "Samples have nan numbers"
def _UpperCAmelCase ( self ) -> int:
"""simple docstring"""
self.check_over_configs(lower_order_final=snake_case )
self.check_over_configs(lower_order_final=snake_case )
def _UpperCAmelCase ( self ) -> Dict:
"""simple docstring"""
self.check_over_configs(lambda_min_clipped=-float("""inf""" ) )
self.check_over_configs(lambda_min_clipped=-5.1 )
def _UpperCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
self.check_over_configs(variance_type=snake_case )
self.check_over_configs(variance_type="""learned_range""" )
def _UpperCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
self.check_over_forward(num_inference_steps=snake_case , time_step=0 )
def _UpperCAmelCase ( self ) -> List[str]:
"""simple docstring"""
lowercase : List[str] = self.full_loop()
lowercase : List[Any] = torch.mean(torch.abs(snake_case ) )
assert abs(result_mean.item() - 0.27_91 ) < 1E-3
def _UpperCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
lowercase : Optional[int] = self.full_loop(use_karras_sigmas=snake_case )
lowercase : Dict = torch.mean(torch.abs(snake_case ) )
assert abs(result_mean.item() - 0.22_48 ) < 1E-3
def _UpperCAmelCase ( self ) -> Dict:
"""simple docstring"""
lowercase : Any = self.full_loop(prediction_type="""v_prediction""" )
lowercase : Union[str, Any] = torch.mean(torch.abs(snake_case ) )
assert abs(result_mean.item() - 0.14_53 ) < 1E-3
def _UpperCAmelCase ( self ) -> Dict:
"""simple docstring"""
lowercase : str = self.full_loop(prediction_type="""v_prediction""" , use_karras_sigmas=snake_case )
lowercase : Tuple = torch.mean(torch.abs(snake_case ) )
assert abs(result_mean.item() - 0.06_49 ) < 1E-3
def _UpperCAmelCase ( self ) -> Tuple:
"""simple docstring"""
lowercase : int = self.scheduler_classes[0]
lowercase : int = self.get_scheduler_config(thresholding=snake_case , dynamic_thresholding_ratio=0 )
lowercase : Optional[int] = scheduler_class(**snake_case )
lowercase : str = 1_0
lowercase : Tuple = self.dummy_model()
lowercase : Any = self.dummy_sample_deter.half()
scheduler.set_timesteps(snake_case )
for i, t in enumerate(scheduler.timesteps ):
lowercase : Union[str, Any] = model(snake_case , snake_case )
lowercase : Union[str, Any] = scheduler.step(snake_case , snake_case , snake_case ).prev_sample
assert sample.dtype == torch.floataa
| 607 | import os
import random
import sys
from . import cryptomath_module as cryptomath
from . import rabin_miller
lowercase_ : Tuple = 3
def A__ ( snake_case_ : int ):
print('''Generating primitive root of p''' )
while True:
SCREAMING_SNAKE_CASE__: List[Any]= random.randrange(3 , snake_case_ )
if pow(snake_case_ , 2 , snake_case_ ) == 1:
continue
if pow(snake_case_ , snake_case_ , snake_case_ ) == 1:
continue
return g
def A__ ( snake_case_ : int ):
print('''Generating prime p...''' )
SCREAMING_SNAKE_CASE__: List[Any]= rabin_miller.generate_large_prime(snake_case_ ) # select large prime number.
SCREAMING_SNAKE_CASE__: int= primitive_root(snake_case_ ) # one primitive root on modulo p.
SCREAMING_SNAKE_CASE__: int= random.randrange(3 , snake_case_ ) # private_key -> have to be greater than 2 for safety.
SCREAMING_SNAKE_CASE__: str= cryptomath.find_mod_inverse(pow(snake_case_ , snake_case_ , snake_case_ ) , snake_case_ )
SCREAMING_SNAKE_CASE__: int= (key_size, e_a, e_a, p)
SCREAMING_SNAKE_CASE__: Union[str, Any]= (key_size, d)
return public_key, private_key
def A__ ( snake_case_ : str , snake_case_ : int ):
if os.path.exists(F'{name}_pubkey.txt' ) or os.path.exists(F'{name}_privkey.txt' ):
print('''\nWARNING:''' )
print(
F'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'
'''Use a different name or delete these files and re-run this program.''' )
sys.exit()
SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Optional[Any]= generate_key(snake_case_ )
print(F'\nWriting public key to file {name}_pubkey.txt...' )
with open(F'{name}_pubkey.txt' , '''w''' ) as fo:
fo.write(F'{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}' )
print(F'Writing private key to file {name}_privkey.txt...' )
with open(F'{name}_privkey.txt' , '''w''' ) as fo:
fo.write(F'{private_key[0]},{private_key[1]}' )
def A__ ( ):
print('''Making key files...''' )
make_key_files('''elgamal''' , 2_048 )
print('''Key files generation successful''' )
if __name__ == "__main__":
main()
| 64 | 0 |
'''simple docstring'''
import random
def _UpperCamelCase ( lowerCAmelCase__: int ) -> bool:
SCREAMING_SNAKE_CASE_ = num - 1
SCREAMING_SNAKE_CASE_ = 0
while s % 2 == 0:
SCREAMING_SNAKE_CASE_ = s // 2
t += 1
for _ in range(5 ):
SCREAMING_SNAKE_CASE_ = random.randrange(2 ,num - 1 )
SCREAMING_SNAKE_CASE_ = pow(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ )
if v != 1:
SCREAMING_SNAKE_CASE_ = 0
while v != (num - 1):
if i == t - 1:
return False
else:
SCREAMING_SNAKE_CASE_ = i + 1
SCREAMING_SNAKE_CASE_ = (v**2) % num
return True
def _UpperCamelCase ( lowerCAmelCase__: int ) -> bool:
if num < 2:
return False
SCREAMING_SNAKE_CASE_ = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in low_primes:
return True
for prime in low_primes:
if (num % prime) == 0:
return False
return rabin_miller(lowerCAmelCase__ )
def _UpperCamelCase ( lowerCAmelCase__: int = 1024 ) -> int:
while True:
SCREAMING_SNAKE_CASE_ = random.randrange(2 ** (keysize - 1) ,2 ** (keysize) )
if is_prime_low_num(lowerCAmelCase__ ):
return num
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : Tuple = generate_large_prime()
print(("Prime number:", num))
print(("is_prime_low_num:", is_prime_low_num(num)))
| 238 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE : Optional[int] = {
"facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json",
"facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json",
"facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json",
"facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json",
"facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json",
"facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json",
"facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json",
"facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json",
"facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json",
}
class snake_case ( lowercase_ ):
"""simple docstring"""
_a = """xmod"""
def __init__( self, _lowercase=30522, _lowercase=768, _lowercase=12, _lowercase=12, _lowercase=3072, _lowercase="gelu", _lowercase=0.1, _lowercase=0.1, _lowercase=512, _lowercase=2, _lowercase=0.02, _lowercase=1E-12, _lowercase=1, _lowercase=0, _lowercase=2, _lowercase="absolute", _lowercase=True, _lowercase=None, _lowercase=False, _lowercase=2, _lowercase=False, _lowercase=True, _lowercase=True, _lowercase=("en_XX",), _lowercase=None, **_lowercase, ) -> Optional[Any]:
super().__init__(pad_token_id=_lowercase, bos_token_id=_lowercase, eos_token_id=_lowercase, **_lowercase )
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = type_vocab_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = position_embedding_type
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = classifier_dropout
SCREAMING_SNAKE_CASE_ = pre_norm
SCREAMING_SNAKE_CASE_ = adapter_reduction_factor
SCREAMING_SNAKE_CASE_ = adapter_layer_norm
SCREAMING_SNAKE_CASE_ = adapter_reuse_layer_norm
SCREAMING_SNAKE_CASE_ = ln_before_adapter
SCREAMING_SNAKE_CASE_ = list(_lowercase )
SCREAMING_SNAKE_CASE_ = default_language
class snake_case ( lowercase_ ):
"""simple docstring"""
@property
def a__ ( self ) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
SCREAMING_SNAKE_CASE_ = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
SCREAMING_SNAKE_CASE_ = {0: 'batch', 1: 'sequence'}
return OrderedDict(
[
('input_ids', dynamic_axis),
('attention_mask', dynamic_axis),
] )
| 238 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.